Response
stringlengths 8
2k
| Instruction
stringlengths 18
2k
| Prompt
stringlengths 14
160
|
---|---|---|
I've not tested it, but something like:$gunzip_result=system("gunzip $gzfile 2>/dev/null");
|
So, OK, the job runs in cron: it fetches compressed files and processes them. If the files are corrupted, it deletes them. Sometimes they are bad on the remote server, in which case they will be downloaded and deleted each time.My cron logs extensively to STDOUT (directed to logfile in .crontab), using STDERR only for things that cause the script to stop: Ilikegetting emails from cron when bad stuff happens; it's just that corrupted files should not be on this list.I need the output from 'gunzip' to tell me if the file is corrupted. However, I am tired of getting emails from cron every time it encounters a bad file. How do I call 'gunzip' so that errors will not trigger emails from cron, while still letting the script that calls 'gunzip' know that it failed?This is probably a pretty easy one, but I'm pretty new to this cron stuff.Important PS: 'gunzip' is called from a Perl script, using$gunzip_result=system("gunzip $gzfile");
if($gunzip_result){
print,"$gzfile is bad: deleting...\n";
unlink $gzfile;
};
|
How can I intercept errors from gzip so cron doesn't see them?
|
not triggering for every 5 minutes when I pushed the feature branch and raise a PRIt does not trigger for a feature branch because the documentation clearly states this:Scheduled workflows run on the latest commit on the default or base branch. The shortest interval you can run scheduled workflows is once every 5 minutes.This part should for sure trigger for a push to themainbranch though:push:
branches:
- mainand that might be redundant with the whole cron schedule. I'm not sure if a scheduled workflow will trigger for commits that have already been verified on push.Pull request against themainbranch should also automatically trigger without the whole cron part:pull_request:
types: [opened, synchronize, reopened]
branches:
- mainIf none of these trigger, first make sure your default branch really ismainand and notmaster.mainis the new default at GH, but your local git installation might still usemaster.See the documentation for more:https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#schedule
|
name: Scheduled Job
on:
schedule:
- cron: "*/5 * * * *" # Runs every 5 minutes
push:
branches:
- main
pull_request:
types: [opened, synchronize, reopened]
branches:
- main
workflow_dispatch: {}
jobs:
scheduled-job:
runs-on: ubuntu-latest
steps:
- name: Print Current Time
run: echo "The current time is $(date)The above github actions workflow YAML is not triggering for every 5 minutes when I pushed the feature branch and raise a PRPlease guide me the reason why the CRON job is not triggered?
|
github scheduled cron job not triggering every 5 minutes
|
As a simple variant, use a watchdog. The program on regular intervals writes to a well-specified file. If the file haven't been updated in a long enough time, the program is unresponsive, and you should kill and restart it.With that said, the best solution is of course to fix the problems that cause the crashes or unresponsiveness. You should have enough logging to be able to pinpoint exactly when and where things go wrong. And perhaps make sure there's a coredump available for crashes, so you can debug it.
|
We have a remote device that is controlled by a C program. This program often fails so we want to introduce some monitoring. Either the program crashes and exits or some bug happens and the program is not responding.We want to set up a cron task or some other scripts for monitoring. What is the best modern practice for communication between C program and bash script or cron? We have access to the source code of this C program, so we can introduce some sort of error messages / events. Should they be written to a file that is later parsed by cron or some other monitoring script - or is this approach obsolete and there is some API or Linux messaging system for communication is such cases?
|
Comunication between C program and script or cron
|
There is a bug where kubernetes dashboard is using API version batchV1beta1 for cronjobs which has been removed in kuberentes version 1.25.I've created a fixed version based on kuberentes dashboard version v2.7.0. I've published it on docker hub:beffe/kubernetes-dashboard:v2.7.0-fix-cj-2You can find the code changes here:https://github.com/kubernetes/dashboard/compare/master...beffe123:kubernetes-dashboard:v2.7.0-fixes
|
I have a kubernetes v1.25 and i cant show the details of my cronjobs anymore on all of my namespace of my kubernetes dashboard.
FYI, it works in command kubectl line i can list my cronjobs and access.
Dashboard version used 2.7.0On my project i modified the api version to the one recommended :
apiVersion: 'batch/v1'
kind: 'CronJob'When i check the logs of my kubernetes dashboard pod, i can see that every time i try to check the details of my cronjob on a namespace through graphical dashboard, an error log pop "There was an error during transformation to sidecar selector: Resource "cronjob" is not a native sidecar resource type or is not supported".Do you have any idea ?
Thank you
|
Kubernetes Cronjob Error not a native sidecar
|
Cron looks good but checkstimezoneof your Kubernetes cluster.K8s clustermight be following theUTCtimezone and hope you are counting the same inlocaltimezone.This cron should work :05 10 31 Mar *but based on the cluster'sdatesetup.
|
I have this cron job running on kubernetes:# cronjob.yaml
apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: loadjob
spec:
schedule: "05 10 31 Mar *"
successfulJobsHistoryLimit: 3
jobTemplate:
spec:
template:
metadata: # Dictionary
name: apiaplication
labels: # Dictionary
product_id: myprod
annotations:
vault.security.banzaicloud.io/vault-role: #{KUBERNETES_NAMESPACE}#
prometheus.io/path: /metrics
prometheus.io/port: "80"
prometheus.io/scrape: "true"
spec:
containers:
- name: al-onetimejob
image: #{TIMELOAD_IMAGE_TAG}#
imagePullPolicy: Always
restartPolicy: OnFailure
imagePullSecrets:
- name: secretIn the above cron expression I have set it to today morning 10.05AM using cron syntax schedule:05 10 31 Mar *- but unfortunately when I checked after 10.05 my job (pod) was not running.So I found it's not running as expected at 10.05 using the above expression. Can someone please help me to write the correct cron syntax? Any help would be appreciated. Thanks
|
Unable to run cron job in kubernets
|
I suggest to usesed:myscript 2>&1 | ts | sed '$a\' >> cron.logThis adds\nat the end of the file only if it doesn’t already end with a newline.--l0b0
|
I'm trying to log both stdout and stderr from my cron task to a custom log file. If there is no output or error, I do not want to log anything. If there is either output or error, I want to log it to a new line and prefix it with the current timestamp.I've tried the followingmyscript 2>&1 | echo "$(cat -)" | ts >> cron.logThis gets me almost what I want. It will log both output and errors from myscript, prefix them with the current timestamp and put them on a new line. The problem is that if myscript produces no output, then because echo produces a new line, I'll get a log entry with just the timestamp on a new line.I want to do this all on the cron line. I do not want to have to modifymyscript.
|
Log output and error from cron script to custom file with timestamp
|
0 6-18/2 ? * MON-FRIIt worked very fine,people can use for their work
|
I have to create a Cron job every two hours, starting from time 6 am PST to 6 pm PST. Also any possibility of excluding weekends?It will be used in databricks.
|
How to create Cron job for every two hours starting from time from 6am to 6pm PST ? Any possibility of excluding weekends?
|
You can just run the same job at an interval of every 30 minutes so that it covers all the timezones. This should work:# run this every 30 minutes
time_zones_with_23 = ActiveSupport::TimeZone.all.select { |tz| tz.now.hour == 23 }.map { |tz| tz.tzinfo.name }
user_list = User.where(time_zone: time_zones_with_23)
|
I want to schedule a cron job that would send emails to all users as soon as deadline for their events ended. Note: Every user have different timezone.The approach i was thinking about:
I have a cron job that will run every day at 11 PM of UTC. This approach does work but every user will receive email according to UTC i.e at 1am, 3am or 4pm. Not according to their timezone.* 23 * * * 'UTC'
|
Schedule Cron job for different timezones rails?
|
In your use case, you have to deploy your python somewhere.If the script takes less than 1H, deploy it onCloud Run JobsIf not, prepare aBatch configurationfor your scriptIn both case, I recommend you to use container to package your code.Then you have to schedule that runtime.Call theCloud Run Job execution APIdirectly with Cloud Scheduler (Be careful, for now, you can't send parameters to your jobs, only trigger a run)Call theBatch APIdirectly with Cloud Scheduler and with the config in the body
|
I would like to get a help from you.
I am trying to deploy my python script to google cloud and execute it as cron.
I am unable to deploy it to google cloud as i am unable to it work.
Can anyone help me with this?
Thanks in advance.
|
How to run Python script in Cron in GCP?
|
There is no difference between the root user and root permissions. All scripts inroot's crontab will run asroot, and all commands therein will also run asroot, with all associated permissions.
|
If a crontab is created for the root user under Linux, usingsudo crontab -e, then anything that's directly run by the crontab will use root permissions - seeIs it possible to make a Bash file run as root in crontab?Does this mean that any commandswithinthe bash script will also inherit root permissions, or will any commands within the bash script need to be explicitly executed with root permissions e.g.sudo docker ps?
|
Do commands run with root permissions, if they're inside a bash script that's executed via a crontab under root
|
I think the best way is to create a script that reads you .env file an runs the command, like this:#!/bash
# This is /my_path/my_script.sh file,
# do not forget to set executable permission by chmod
# Reading vars
. /my_path/my_env.env
# Calling the command
curl -Ssi -X POST -u "${variable1}:${variable2}" https://example.com...and your crontab line will be like this:2 11 * * * /my_path/my_script.shor alternatively in not so readable manner, directly in the crontab:2 11 * * * . /my_path/my_env.env; curl -Ssi -X POST -u "${variable1}:${variable2}" https://example.com...
|
I have a crontab and .env file. And I want to reach .env variables from crontab. Is it possible?.envvariable1=value1
variable2=value2crontab2 11 * * * curl -Ssi -X POST -u 'value1:value2' https://example.com...
|
Read .env variables in crontab
|
AWS uses the extended CRON expression format:Please notice, there are 6 fields in the expression:Minutes,Hours,Day of month,Month,Day of weekandYear.In your case, you provide only 5 values. I'm guessing you were most likely usingcrontab.guruto create your cron expression, meaning that you want an event to fireAt 00:00. In that case, for AWS you would want to have something like this:0 0 * * ? *.
|
I want to deploy function to AWS Lambda with using serverless framework in NodeJS/Typescript. Here is my serverless.yml:service: backend
plugins:
- serverless-webpack
provider:
name: aws
region: eu-central-1
runtime: nodejs14.x
stage: dev
functions:
createDailyStatistics:
handler: dist/services/schedules.scheduleDailyStatistics
events:
- schedule:
rate: cron(0 0 * * *)
enabled: truecan someone tell me, why after launchserverless deployi got an error like this:CREATE_FAILED: CreateDailyStatisticsEventsRuleSchedule1 (AWS::Events::Rule)
Parameter ScheduleExpression is not valid. (Service: AmazonCloudWatchEvents; Status Code: 400; Error Code: ValidationException; Request ID: xxx; Proxy: null)My expression -0 0 * * *is a standard cron expression but AWS not handle this? I want to launch this functino on every day at midnight.Thanks for any help!
|
AWS Cron schedule expression
|
I did exactly the same you do and works. However, I cannot see how is the other parts of your code. Here is the complete code.app.module.tsimport { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ScheduleModule } from '@nestjs/schedule';
@Module({
imports: [ScheduleModule.forRoot()],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}app.service.tsimport { Injectable } from '@nestjs/common';
import { SchedulerRegistry } from '@nestjs/schedule';
import { CronJob } from 'cron';
@Injectable()
export class AppService {
private readonly logger = new Logger(AppService.name);
constructor(private schedulerRegistry: SchedulerRegistry) {}
async testCron() {
const job = new CronJob('2 * * * * *', () => {
this.logger.log('My cron running...');
});
this.schedulerRegistry.addCronJob('sec', job);
job.start();
}
}And here is the consult using Postman:GET http://localhost:3000/cronThen is printed in the console. Pay attention it's not printed each 2 second but every second 2.[Nest] 15287 - 05/20/2022, 6:13:02 PM LOG [AppService] My cron running...
[Nest] 15287 - 05/20/2022, 6:14:02 PM LOG [AppService] My cron running...
[Nest] 15287 - 05/20/2022, 6:15:02 PM LOG [AppService] My cron running...
|
I am trying to implement cron in Nest application. I am adding cron dynamically as per the documentation as I want to perform some cron operation based on POST request. So for that I have added cron dynamically usingSchedulerRegistrybut when I am making POST request cron is not running.Below is my code:app.controller.tsimport { Controller, Get, Post } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Post('cron')
testCron(){
return this.appService.testCron();
}
}app.service.tsimport { Injectable } from '@nestjs/common';
import { Cron, Interval, SchedulerRegistry } from '@nestjs/schedule';
import { CronJob } from 'cron';
@Injectable()
export class AppService {
constructor(private schedulerRegistry:SchedulerRegistry){}
async testCron(){
const job = new CronJob('2 * * * * *', () => {
console.log("My cron running...");
});
this.schedulerRegistry.addCronJob('sec',job);
job.start();
}
}Why this cron job is not running on POST request as console statement is not showing?
|
Cron is not running in NestJs
|
Make your script run every 30 minutes. On success, check if it is 11am before outputting success.if [ $Status == "200" ]; then
if [ $(date +%H%M) == "1100" ]; then
echo "success"
fi
else
echo "error"
fiNote: This checks for exactly 11:00 am. If your script may take longer than 1 minute to reach this point, save the time somewhere at the beginningtime="$(date +%H%M)"and check against it afterwardsif [ "$time" == "1100" ].Alternatively, if you want to keep the actual time at which to behave differently outside the script, you can introduce a parameter that is set only (or in one way) on the 11 am run, but not (or in another way) on the other runs.This requires you to still have multiple cron jobs, but with different parameters to the same script.0 11 * * * /home/username/script.sh yes
30 11 * * * /home/username/script.sh no
*/30 0-10,12-23 * * * /home/username/script.sh noWithin the script you need to check the parameter provided.printsuccess="$1"
if [ $Status == "200" ]; then
if [ $printsuccess == "yes" ]; then
echo "success"
fi
else
echo "error"
fi
|
First script runs once everyday at 11am and notifies that everything is working fine with "success" message.if [ $Status == "200" ]; then
echo "success"
else
echo "error"
fiSecond script runs every 30 minutes and doesn't print anything unless there's an error. Basically it keeps on checking every 30 minutes if everything's working fine and notifies me of an error only if anything is down.if [ $Status != "200" ]; then
echo "error"
fiBoth the scripts have almost exactly the same code. But I'm using 2 different scripts because of different outputs I want at different times. So is there a way to combine both the scripts?To be more clear, if possible, I want a single script that can send a success message everyday at 11am while also running every 30 minutes without sending that success message again and again and then only send error message if anything's down.In crontab it's like this:0 11 * * * /home/username/script1.sh
*/30 * * * * /home/username/script2.sh
|
How to combine these 2 scripts and run multiple cron jobs for the same script to get different outputs?
|
You need to use the dbt binary directly, your cron should look something like this12 11 * * * cd ~/path/to/dbt-folder && ~/path/to/.venv/bin/dbt run
|
I want to create a Cron job that runs DBThttps://www.getdbt.com/on the schedule. Normally, I run it in a virtual environment withdbt runcommand in a dbt folder.I've created the cron job in crontab12 11 * * * cd ~/path/to/dbt-folder && ~/path/to/.venv/python dbt runAnd it's not working.Can someone provide some help on how to configure DBT job in crontab?Thanks
|
How to run dbt from Crontab in Ubuntu?
|
The*/5syntax means "every 5 units, starting from 0". So, if you use it in the hour position, it will match hours 0, 5, 10, 15, 20.I'm assuming what you actually want is a strict 5 hour interval. So after hour 20, you want the next run to be at 20 + 5 hours, so at 1AM not midnight. If that's correct, there isn't an easy way to make cron work like that. It can do even intervals of all divisors of 24 though: every 2 hours, every 3 hours, every 4 hours, every 6 hours, every 12 hours.To get the 5 hour interval, one possible workaround is toschedule the cron job to run every hourat the start of your script that the cron job runs, add extra logic tocheck if it should run this hour. For example, you could take the current time, and calculate the hours since epoch. And exit early unless the calculated number is divisible by 5.
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be abouta specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic onanother Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.Closed2 years ago.Improve this questionI would like to run a cronjob every 5 hours.Now it's 11:54pm..Checking the crontab guru, this0 */5 * * *seems to be correct, but the site also mentions something like thisnext at 2022-01-07 00:00:00I would like to know why? Does it mean it runs the script no matter what at midnight(00:00:00) ? Doesn't make sense.
|
How to run a cron job every 5 hours (on Linux) [closed]
|
I would suggest using pm2 in production. It definitely handles crashes better than nodemon
|
I am hosting a node js app on vps and I want to restart app if app crashed.
is it good to usenodemoninstead ofnodeforstartinpackage.jsonfile?
(performance and memory usage on production)"scripts": {
"start": "node db",
"dev": "nodemon db"
}alternatively, ispm2suggestedhereis good for both server crash and app crash?
|
restart node app after app crash using nodemon
|
Executing the pipeline during the last 6 days of the month:Since not every month would have 31 days, you want to execute the pipeline on the last 6 days independently from the number of days in the month.Azure pipelines useNCrontabwhich does not provide support for specifying days relative to the end of the month as confirmed by the author inthis issue.One possible solution (following the suggestion inthe following comment) is to use a range of days that include the last six days in the worst case (February ending on the 28th) which you would express as23-31.Then, you must have a task in your pipeline that checks that the current date is within the range of the last 6 days of the current month, and stop the pipeline if it is not.As a result, your pipeline will be executed for the last 6 days of the month in the best case and for the last 9 days in the worst case but this will be handled by the additional task explained in the previous sentence.Running the pipeline using schedule triggers:If you want to run your pipeline by using schedule triggers, you need to disable PR and CI triggers.pr: none
trigger: none
|
I am trying to configure azure pipeline schedules for running it on a specific day but it is not taking day from 27 to 31.Please refer below screenshot for better understanding the issue.trigger:mainpool:
vmImage: ubuntu-latestschedules:cron: "0 18 26-31 * *"
displayName: Daily midnight build
branches:
include:main
always: trueThank you
|
Azure Pipelines Schedule to Run on specific day is not working
|
Usingatcommand:#!/usr/bin/env bash
script_path="$(realpath -s -- "$0")"
# start script
...
# end script
echo "rm -- \"$script_path\"" | at "now + 5 minutes"Using background process with sleep:#!/usr/bin/env bash
script_path="$(realpath -s -- "$0")"
# start script
...
# end script
( sleep 300 && rm -- "$script_path" ) &Using parentselfdestructprocess:Write a little scriptselfdestructthat looks like:#!/usr/bin/env bash
dt="$1"; shift
"$@"
( sleep "$dt" && rm -- "$1" ) &and run your script with$ selfdestruct 300 /path/to/script arg1 arg2 arg3
|
I am writing ashell scriptwhere I create a fileABC.txtin a path/path/to/ABC/ABC.txt.Now I at the end of the script, I want to schedule a cron job to delete this file after 5 minutes (just once, not recurring).I cannot adsleepof 5 minutes in this script as it is being used by multiple users on server for multiple paths/files. And 5 minutes after the user executes this script the correspondingfile.txtfrom respective path should get deleted.What I read from a cronjob is you can trigger a script usingcrontab -eand then providing periodic notation of job and path to scriptH/5 * * * * /bin/sh /path/to/ABC/ABC.txt.Can someone tell me how to schedule such functionality using cron. If there is a better way to do this please suggest.
|
Delete a newly created file using shell script after 5 minutes
|
The easiest way to "make a copy of an instance" is tocreate an Amazon Machine Images (AMI).The AMI takes a copy of all disks attached to the instance.Then, you canlaunch a new instance from the AMIand the new instance will have an exact copy of the disks from the original instance. This includes the operating system, applications, data, cron settings, etc because the disk was totally copied.See:Create an Amazon EBS-backed Linux AMI - Amazon Elastic Compute Cloud
|
I need to make a test environment of a current running system.In order to do this, I'm thinking of making a copy of the instance but, does the cron schedules will be copied as well?
Or do I need to set up all the server settings and cron jobs?
|
If I make an EC2 instance copy, the server settings like cron schedules are also copied?
|
Cloud Scheduler:https://cloud.google.com/scheduleris the service you're looking for. It'll let you schedule events on a timer like you're looking to do.
|
I have a service in Goole Run Cloud. I run make it do work by sending HTTP request to the special url.But I want to run that code very N minutes. So I'm searching the proper way to do it.I need something like Cloud Cron that I can configure to make a special request every N minutes.
|
How to execute Google Cloud Run service every N minutes?
|
It doesn't work that way, as you need to setup Django for these command to workYou have 2 optionsImplement this as amanagement commandSetup Django manually as the start of your script.import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
django.setup()
|
I have a model inside tools app calledApiKeysand tried to update the model in specific time intervels. I used django-crontab for this purpose.CRONJOBS = [
('*/1 * * * *', 'tools.cron.reset_api_calls','>>logs.log')
]function -from .models import ApiKeys
def reset_api_calls():
try:
keys = ApiKeys.objects.all()
for key in keys:
key.api_calls = 0
key.save()
except Exception as e:
print(e)model -class ApiKeys(models.Model):
key_token = models.CharField(max_length=50, primary_key=True)
api_calls = models.IntegerField(default=0)
las_used_date = models.DateTimeField(default=timezone.now)But it gives error log -no such table: tools_apikeysNote: The table does exist in database and accessible through django-shell and views.py as well.
|
Django-crontab can't make model query
|
Since you want from 0 to 30 minutes, all you have to do is instead of every minute in the expression change it to 0-30 minutes with every 5 minutes step.0-59/5 5-6 * * *You can refer tohttps://crontab.guru/for checking next values also. Since it gives only 5 next values, you can change the step up from 5 to 20 for better clarity.
|
I have a requirement where my DAG has to run every 5 minutes from 5 AM to 6:30 AM. I know how to schedule with crontab it if it is from 5 AM to 6 AM like */5 5-6 * * * but I have to do this for time interval 5 AM to 6:30 AM.
Any help is appreciated.
|
crontab expression to schedule a DAG to run in specific time interval
|
You can usethis siteto find the correct cron expression.According this site try this cron expression:@Scheduled(cron = "0 0 * ? * *")Also try this as alternative:@Scheduled(cron = "0 0 */1 * * *")
|
I need to run a job in spring boot for every 9 hours. I have used @Scheduled(cron = "0 */9 * * *") for running the job .But when the run the application I am getting error as "Encountered invalid @Scheduled method 'data': Cron expression must consist of 6 fields"Please anyone help me out on this
|
Spring Scheduled cron job for every 9 hrs after starting the server(IF server starts at 2:15 PM and next task should happen at 11:15Pm)
|
You probably already got an answer or given up.
Anyway for future reference:
Yes, the package you are trying to install is amd64, you just need to download the correct architecture one.
In the release section you can find the ARM package, it works fine on Raspihttps://github.com/cronitorio/cronitor-cli/releases/tag/28.7
|
i'm trying to use cronitor (a server that monitors you cron jobs) on my raspberry pi zero.
The installation process for cronitor given in the doc fails when I run the last line:# Install CronitorCLI
curl -sOL https://cronitor.io/dl/cronitor-stable-linux-amd64.tgz
sudo tar xvf cronitor-stable-linux-amd64.tgz -C /usr/bin/
sudo cronitor configure --api-key [[[my private key here]]]I get this error/usr/bin/cronitor: 2: /usr/bin/cronitor: Syntax error: Unterminated
quoted stringI guess this is caused by the incompatibility of the amd64 binary for raspberry? Is there another way to install this? Thanksnote: tested on raspberry pi zero and 4
|
run cronitor on raspberry crontab
|
The first item in a cron schedule is theminute. The first*in your cron schedule* 7,19 * * *matchesevery minutebetween 7:00 and 7:59 (and also every minute between 19:00 and 19:59). In therory, your cron job should not run twice, but 120 times per day using this schedule.To execute your cron job atexactly7:00 and 19:00, use0 7,19 * * *as schedule.For reference, theKubernetes documentation onCronJobresourcescontains more information on the cron schedule format and itself links to theBSD cron documentation.
|
I have a cronjob that I want to execute twice a day, at 7h and 19h.Here is the definition.apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: pamela
namespace: influx
spec:
schedule: "* 7,19 * * *"
concurrencyPolicy: Replace
jobTemplate:
spec:
template:
spec:
containers:
- image: registry.gitlab.com/xxx/pamela:latest
envFrom:
- secretRef:
name: pamela-env
name: pamela
resources:
volumeMounts:
- mountPath: /raw
name: pamela-claim
subPath: raw
- mountPath: /log
name: pamela-claim
subPath: log
restartPolicy: Never
volumes:
- name: pamela-claim
persistentVolumeClaim:
claimName: pamela-claim
nodeSelector:
kops.k8s.io/instancegroup: nodes
imagePullSecrets:
- name: gitlab-registryThing is when it runs, it runs 3 times :at 2021-01-06T07:57:00Zat 2021-01-06T07:58:00Zat 2021-01-06T07:59:00ZIt is to be mentioned that my job execution time is about 22secWhy is it happening ?
|
Kubernetes CronJob is executing 3 times instead of 1
|
First of all you don't need to query every second because the cron has only a one minute resolution.Next, comparing a cron scheduler expression to a timestamp is not a trivial task.
I'm not aware of any PostgreSQL module that would be able to parse the cron expressions.There are two options, either you write your own function to do the comparison, or else you use a external library in the programming language you are using to do the comparison outside of the Database.Here you will find an example implementation of such a function for Oracle that could easily be ported to PostgreSQL:SQL Query to convert cron expression to date/time formatIt is incomplete because it doesn't handle complex expressions like */5 or 5,10,15 for individual fields of the cron expression but this is where I would start.
|
I'm building a cron-as-a-service, to allow users to input their cron expression, and do some stuff periodically.Here's a simple version of my table:create table users (
id serial not null primary key,
-- `text` seems the most straightforward data type, any other suggestions?
cron text not null,
constraint valid_cron_expression CHECK (cron ~* '{some_regex}'),
-- snip --
-- maybe some other fields, like what to do on each cron call
)My backend runs a SQL query every minute. How can I query all the rows whosecronfield match the current timestamp (rounded to the closest minute)?Edit: users input thecronfield as acron expression, e.g.5 4 * * *.Edit 2: corrected the fact that cron time resolution is minute, not second.
|
SQL: Store and query `cron` field
|
Use*/2for day of the month, like so:01 23 */2 * * command_nameThis runs at 23:01 on the 1st, 3rd, ..., 31st of every month.To run two cron jobs on alternate days:01 23 1-31/2 * * command_name1
01 23 2-30/2 * * command_name2SEE ALSO:The time and date fields are:field allowed values
----- --------------
minute 0-59
hour 0-23
day of month 1-31
month 1-12 (or names, see below)
day of week 0-7 (0 or 7 is Sunday, or use names)A field may contain an asterisk (*), which always stands for
"first-last".
...
Step values
are also permitted after an asterisk, so if specifying a job to be
run every two hours, you can use "*/2".
|
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed3 years ago.Improve this questionI want to run a cronjob to run every night and run a backup script but I want to keep two days of backups before I replace the oldest one.
The only way I can think of doing this is doing a day of the week cronjob and running two cronjobs each replacing the one that itself did two days before.
Is there an easier way to do this?
|
Best way to schedule job to run every other day? [closed]
|
The server is in MST standard time... I want thescript.phpto run from 6:00 AM IST to 7:00 PM IST.Ok, so...06:00 IST is 17:30 MST (previous day)19:00 IST is 06:30 MST (same day)This presents two problemsIt crosses the midnight boundary, andThe 30 min part of the offset makes it very difficult to create a repeating 15 minute pattern that starts / stops at the right time.The easy option is to ask your hosting provider to configure your server's timezone or try and use theCRON_TZenvironment variable if available (probably not with Godaddy).CRON_TZ=Asia/Kolkata
*/15 6-18 * * * /usr/local/bin/php -q /home/ddruva/public_html/site_data/script.phpOtherwise, you're left with something (ugly) like this# 5.30pm and 5.45pm
30,45 17 * * * /usr/local/bin/php -q /home/ddruva/public_html/site_data/script.php
# Every 15 minutes from midnight till 6am and from 6pm till midnight
*/15 0-5,18-23 * * * /usr/local/bin/php -q /home/ddruva/public_html/site_data/script.php
# 6am and 6.15am
0,15 6 * * * /usr/local/bin/php -q /home/ddruva/public_html/site_data/script.phpWith this approach, you're probably going to run into issues when your server changes between standard and daylight savings time and to be honest, I don't really have an answer for that.
|
I am trying to run a PHP file every 15mins from 6PM. I have set cronjob like this:*/15 18 * * * /usr/local/bin/php -q /home/ddruva/public_html/site_data/script.phpcan someone confirm if this script will run at 6 PM and after that every 15mins?The server is in MST standard time. So I have set 6 PM. I want the script.php to run from 6:00 AM IST to 7:00 PM IST. So I have set 6 PM MST.In Godaddy, the process is not happening. Is there a way to check the log if cronjob has run successfully?Thanks!
|
Schedule a simple php file on Cronjob on Godaddy
|
Anyone know why it creates these tilde (~) files?That would be because of the-boption you are specifying torsync. Its purpose is to request exactly that (creation of backup files for destination files that are being replaced).Also anyone know a quick way to delete them?If there is no subdirectory structure to deal with (for example, if you have presented the full list of files), thenrm /path/to/the/directory/*~would be sufficient. If you need to clean up backup files in subdirectories of that directory, too, thenfind /path/to/the/directory -name '*~' -deletewould handle it.
|
I run the following daily crontab:rsync -e 'ssh -p xx' -ab --inplace --delete[email protected]:/home/myname/backup/ /media/internal/myname/backup/It creates these files:-rw-r--r-- 1 myname myname 432M Oct 1 00:01 monthly-db-backup.tar.gz
-rw-rw-r-- 1 myname myname 431M Sep 1 00:00 monthly-db-backup.tar.gz~
-rw-r--r-- 1 myname myname 74 Sep 27 10:08 monthly.py
-rw-rw-r-- 1 myname myname 74 Aug 24 2017 monthly.py~
-rw-r--r-- 1 myname myname 1.5M Oct 11 00:00 domain.sql
-rw-r--r-- 1 myname myname 1.5M Oct 10 00:00 domain.sql~
-rwxr--r-- 1 myname myname 8.0K Sep 27 10:18 sessionbackup.db
-rwxrw-r-- 1 myname myname 8.0K Jun 5 2019 sessionbackup.db~Anyone know why it creates these tilde (~) files? Also anyone know a quick way to delete them?
|
Why does rsync create ~ files?
|
This is the cron you described:* 0/30 0-8 ? * *
|
I have a job running in spring boot and I want to run it every 30 minutes between 12 AM and 8 AM starting at 12 AM. I am struggling to figure out the cron-expression that can be used to achieve this.
|
Cron expression for a job that runs every 30 minutes in a specific time window
|
A more 'canonical' way to tackle this problem in .Net is using the Task Parallel Library instead of manually controlling threads. The console program below illustrates how you would run 6 threads on background threads, with a one second delay between them.class Program
{
public async static Task Main()
{
var cts = new CancellationTokenSource();
List<Task> tasks = new List<Task>();
for (int i = 0; i < 6; i++)
{
tasks.Add(Task.Run(() => DoWork(cts.Token), cts.Token));
await Task.Delay(1000);
}
Console.WriteLine("Press ENTER to stop");
Console.ReadLine();
Console.WriteLine("Waiting for all threads to end");
cts.Cancel();
await Task.WhenAll(tasks);
}
public static void DoWork(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
Console.WriteLine($"Doing work on thread {Thread.CurrentThread.ManagedThreadId}");
Thread.Sleep(10000); // simulating 10 seconds of CPU work;
}
Console.WriteLine($"Worker thread {Thread.CurrentThread.ManagedThreadId} cancelled");
}
}Asynchronous programming using the Task Parallel Library is explained pretty wellin the documentation
|
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed3 years ago.Improve this questionThe usecase is pretty simpleI have this for starting the threadsMain classfor (int x = 1; x <= numThreads; x++)
{
new ThreadComponent(x, this, creator).init();
}Thread classpublic void init()
{
thread = new Thread(doLogic);
thread.IsBackground = true;
thread.Start();
}
void doLogic()
{
while (true)
{
doLogicGetData();
}
}Idea is that thread execution takes approx. 6 seconds
I want 6 threads that start at 1 second interval1------1------
2------2------
3------3------
4------4------
5------5------
6------6------I saw a lot of ideas about using timers or cronjobs but i do not know how to implement them in a proper way
|
Is there a best method to implement a delay in between threads? [closed]
|
This cron will run every minute and task will be bound with condition.
If you need different cron job then you can generate using thiswebsite.@Scheduled(cron = "0 0/1 * 1/1 * ? *")
protected void performTask() {
if (condition)//if value matches with database value
{
//perform the task
}
}
|
What I tried:@Scheduled(cron="* * * 08 04 2099")I want cron expression that never executes.can any one help me with the expression.Thanks in advance...!
|
scheduled cron expression that never runs
|
Look at running a cronjob inside the pod instead of kubernetes CronJob. That way you don't have to bother about launching a new pod every minute.
|
I'm starting in Kubernetes and I have a question about the CronJob, in my project I need a cron job to be launched every minute. On many tutorials people use the CronJob resource, I set it up and I see that every minute a pod is created to perform the command and is then destroyed, and that indefinitely.
I wonder if in my case (every minute) it's interesting to use the Kubernetes CronJob resource knowing that every minute a pod is created by pulling an image etc.... I find the process a bit cumbersome, isn't it better to have a simple pod executing the cron in the traditional way?
|
Deployment pod or CronJob for a job to be done every minute?
|
The first Monday of the month falls on one (and only one) of the dates from the first to the 7th inclusive. Then the cron expression will be easy to get it.Suppose it should be0 0 8 1-7 * Tueand the below is my test, it shows the first five dates.
|
How could I create an timer trigger with Azure Functions(version 3 and .NET Core)that must be executed every first Tuesday from every month at 8 AM. Starting from now(05/08/2020)this must be the next five occurrences:2020/06/02 Tue 08:00:002020/07/07 Tue 08:00:002020/08/04 Tue 08:00:002020/09/01 Tue 08:00:002020/10/06 Tue 08:00:00By usingwww.cronmaker.com, I've next NCRONTAB:0 0 8 ? 1/1 TUE#1 *But then I've next exception:The schedule expression0 0 8 ? 1/1 Tue#1 *was not recognized as a valid CRON expression or TimeSpan string.Then I've start changing the CRON expression to next varations:CORNResult0 0 8 ? 1/1 Tue#1Error from above0 0 8 * 1/1 Tue#1Error from above0 0 8 1/1 Tue#1 *Error from above0 0 8 * 1/1 Tue 1Error from above0 0 8 ? 1/1 Tue 1Error from above0 0 8 * 1/1 Tue/12020/05/29 08:00:00 - 2020/05/30 08:00:000 0 8 * * Tue/22020/05/30 08:00:00 - 2020/06/02 08:00:000 0 8 * 1/1 Tue/22020/05/30 08:00:00 - 2020/06/02 08:00:000 0 8 ? 1/1 Tue/2Error from aboveSo every expression I've made, would not work as expected. My question is now: What's the correct expression?
|
NCRONTAB for every first tuesday of every month for an Azure Function
|
I saw your images and I tested your cron expressionhereand It gives an error i.eSupport for specifying both a day-of-week AND a day-of-month parameter is not implemented.Right Cron Expression0 30 16 * * ?It specify that Your job is trigger 16:30: 00 pm every day.Also as per@Jason'sanswer you also have to use@EnableSchedulingto your configurationclass.Reference:Cron Expression
|
I was tried to implement scheduler with setting for every day. Then I build to a jar file and running with "java -jar". I trying on my computer to still alive until 2 days for test it. Yesterday it's works. But when I look today is not running. Refer from thishttps://riptutorial.com/spring/example/21209/cron-expression.import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
import java.text.SimpleDateFormat;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class Scheduler {
private static final Logger log = LoggerFactory.getLogger(Scheduler.class);
@Scheduled(cron = "0 0 18 * * ?")
public void currentTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
log.info("Current Time = {}", dateFormat.format(new Date()));
log.info("Excel File has been generated");
}
}this log on the second day
|
spring cron scheduled not running in the second day
|
Put the argument toechoin single quotes rather than double quotes, so there won't be any evaluation of$(...)inside it.There's also no need to includecrontab -rin the command that's piped tocrontab -.bash -c "crontab -r; echo '* * * * * /usr/bin/wget -o /backups/\$(date +\%F_\%R).sql 127.0.0.1:8000/api/export/full' | crontab -"
|
I'm using a bash oneliner to create a cronjob that saves files to a path that depends on the current time, hence I'm usingdate. However, thedateexpression is evaluated when I insert the cronjob, while I want thedateexpression to be evaluated when cron runs the job.My command is like this:bash -c "(crontab -r; echo \"* * * * * /usr/bin/wget -o /backups/\$(date +\%F_\%R).sql 127.0.0.1:8000/api/export/full\") | crontab -"How can I alter this command to achieve this?
|
How to insert cronjobs using bash without evaluating command?
|
In general you can not do this. You need to create endpoint, and then run that url.
|
So I have this in my cron.yaml:cron:
- description: "Google analytics data collection"
url: /usr/bin/python3.7 /home/amng853/ruby-website/google_analytics_info.py
schedule: every 1 hoursbut it keeps returning:ERROR: (gcloud.app.deploy) Server responded with code [500]:
Internal Server Error.
<h3>Server Error</h3><p>A server error has occurred.</p>when I deploy the cron.yaml and I don't know what to do.I also tried to user python3 instead of python3.7 path but still displays the error. (Yes I have python3.7 and python3 installed)
|
How can I make a cron.yaml file to run python script every hour for google cloud app engine
|
You can set the full path toclogandaccess.txtto be sure what you run and where you write.Example cron record:5 10 * * * /usr/local/sbin/clog /var/log/messages.log | /usr/bin/grep -a user1 >> /path/to/access.txt
|
Does crontab have an argument for creating cron jobs usinggrepcommand to extract some data from text ?this my command :clog /var/log/messages.log | /usr/bin/grep -a user1 >> access.txtwhen i execute this command ; the file text access.txt will be created with the content i needin cron job , the file will be created without content
|
How to create a cron job using cron to grep some file
|
You can't combine them in one record. The times do not match on any way. Of course if you have more jobs this eventually can be possible (depend on intervals)
|
Hello I am configuring jobs in GCP following the google cloud guide:https://cloud.google.com/scheduler/docs/configuring/cron-job-schedules?&_ga=2.226390674.-907001748.1582817924#defining_the_job_scheduleI have to configure a job which will be executed once on weekdays at 6am and once on weekends at 5am. I am not pretty sure if it is possible to configure this for several intervals of time with something like an and statment:0 5 * * 1-5 # monday to friday 5 am.
0 6 * * 6,0 # saturday and sunday 5 am.In what way I can combine this intervals, besides that I need to add others ones but I am not pretty sure how can I do this.Thanks.
|
Configure a cron schedule for different intervals (hour and days)
|
What you are doing now is scheduling a job to run twice daily.
However, you can alsomanually dispatch a jobto run at that instance (or as soon as a runner is free to handle your job).You can create a controller action so that when the button is clicked, the controller dispatch the job. For example,<?php
namespace App\Http\Controllers;
use App\Jobs\ResendAttachment;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class ExampleController extends Controller
{
/**
* Resend attachment.
*
* @param Request $request
* @return Response
*/
public function resendAttachment(Request $request)
{
ResendAttachment::dispatch();
}
}
|
I have created commands inkernel.phpwhich is runningtwiceDaily(). I also want to attach it with button so I can run this command by clicking on that button. When I click on on button it should run at that moment.Currently, I have just created twiceDaily command I need better way to implement button idea.kernel.phpprotected function schedule(Schedule $schedule)
{
$schedule->job(new \App\Jobs\ResendAttachment)->twiceDaily(1, 13);
}I want to run command by cron job on server and by button also.
|
How i can run command by run schedule and by button also?
|
It turns out thaterror_logactuallywasbeing called, but because it was activated by a system cron, the error log output was being sent to a different error log file than the usual one.To fix it, I used the error_log function'sthird parameterto send the output to a custom log file.
|
I'm trying to schedule that runs every five minutes.The code below successfully schedules the cron, and it shows up in WP Crontrol, but "Doing a cron!" never appears in the error log.What's going wrong?add_action('do_cron_stuff_event', 'do_cron_stuff', 10, 2);
function do_cron_stuff()
{
error_log('Doing a cron!');
}
add_filter('cron_schedules', 'cron_stuff_add_5_minute_cron_interval');
function cron_stuff_add_5_minute_cron_interval($schedules)
{
error_log("cron_stuff_add_5_minute_cron_interval called");
$schedules['five_minutes'] =
[
'interval' => 300,
'display' => esc_html__('Every Five Minutes')
];
return $schedules;
}
register_activation_hook(__FILE__, 'cron_stuff_plugin_activation');
function cron_stuff_plugin_activation()
{
error_log("cron_stuff_plugin_activation called");
if (wp_next_scheduled('do_cron_stuff_event') === false)
{
wp_schedule_event(time(), 'five_minutes', 'do_cron_stuff_event');
}
}
register_deactivation_hook(__FILE__, 'cron_stuff_plugin_deactivation');
function cron_stuff_plugin_deactivation()
{
error_log("cron_stuff_plugin_deactivation called");
wp_clear_scheduled_hook('do_cron_stuff_event');
}
|
Why is error_log not being called during my cron?
|
Generally speaking (python) Script is location-sensitive. This is related to always using absolute paths in a script, but not quite the same. Your cron job may need to cd to a specific directory where the script is stored before running it.When Cronjob runs it uses your home directory as current directory. So if you were to put your script in your home directory, it will work. In this case the script was using a relative path, assuming that it was relative to the location of the script but it was in fact relative to the root of your home directory because that was the working directory that cron was using, which is why the script worked when it was in the root of my home directory.So if you have to run it in a directory other than your home directory, in your cronjob you will need to cd to your script directory and run it as in this example:* * * * * cd /var/www/clientfolder/ && /usr/bin/python /var/www/clientfolder/your_python_script.py >> /var/www/clientfolder/your_python_script.logit is important you understand why. It should now work!If you have other issue not related to Script Execute Environment you may want to read this very good articleCronJob not runningSource:https://www.digitalocean.com/community/questions/unable-to-execute-a-python-script-via-crontab-but-can-execute-it-manually-what-givesBest of luck
|
i have written a python script 2.7 version, in an Ubuntu OS it will successfully run if I execute it manually, but when I put it in a cronjob it will not work - You will get random library path or module not found error depending what you import/include. I have read stackoverflow almost the same question but the solution provided still does not work for me.Python script not executing in crontabIt is just a simple error, but at first it is difficult to know why.Traceback (most recent call last):
File "/var/www/project/delete.py", line 263, in <module>
pyquery('new')
NameError: pq 'new_data' is not defined
|
Unable to execute a python 2.7 script via crontab, but can execute it manually. What gives?
|
As quoted in crontab manual"The time used for writing into a log file is taken from the local
time zone, where the daemon is running."So your cronjob will be running according to your local timezone i.e. Local time.You can read more herecrontab(5)
|
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed4 years ago.Improve this questionFollowing is the result of the command,timedatectl, which lists different "types" of time.Local timeUniversal timeRTC timeWhich time do thecrontablisten to as my cron-job is not running.$ timedatectl
Local time: Thu 2019-12-26 15:43:38 IST
Universal time: Thu 2019-12-26 10:13:38 UTC
RTC time: Thu 2019-12-26 10:13:39
Time zone: Asia/Kolkata (IST, +0530)
System clock synchronized: yes
systemd-timesyncd.service active: yes
RTC in local TZ: no
|
Which time does the `crontab` listen to? Local, Universal or RTC time? [closed]
|
Your expression"0 1 0 * * ?"means: At 00:01:00am every dayAs per your requirement : At 01:00:00am, on every Sunday, every monthUse:0 0 1 ? * SUN *Follow thishttps://www.freeformatter.com/cron-expression-generator-quartz.htmlfor more detail.
|
I have this code.Thiscronmessage means "do this method every Sunday in 01.00 a.m." or I make a mistake translating this?@Scheduled(cron = "0 1 0 * * ?")
private void notificationsScheduler() {
//implementation
}
|
Translating and understanding the @Scheduled cron message
|
Edited:Agree with Simon, you can configure 2 separate cron schedules:1st expression(skipping Thursday) - “At minute 0 past hour 4 and 14 on every day-of-week from Monday through Wednesday and every day-of-week from Friday through Sunday.”0 4,14 * * 1-3,5-7Cron expression for Thursday:0 14 * * 4
|
GoalCreate a Cron expression that will run a task at 2 pm and 4 am every day to run a Splunk alertExcept for only run the 2 pm task on Thursday (don't run the task a 4 am on Thursday).QuestionIs this an expression that can be represented in a single expression? (if so how).
|
Does Cron have a way to include all except one case
|
I think you might need to rethink why you actually need a cron job.
Why do you have old log files inside of your container? One of the best practices with building applications inside containers is the fact of logging everything towards stdout/stderr. This way you keep the paradigm of 1 container = 1 process and your log management is a responsibility of docker and/or your host.You can do this fairly easy by either:reconfiguring your application to log to /dev/stdoutlinking your application log file /var/log/nginx/access.log to /dev/stdout in your dockerfileln -sf /dev/stdout /var/log/nginx/access.log
ln -sf /dev/stderr /var/log/nginx/error.logIf you actually need to log towards a location inside your container, a good practice could be to log towards a shared volume. Then run a cron job that spins up a container which also mounts this volume and cleans the logs. You can schedule this clean-up container with a cron job.If you use some kind of orchestrator like Kubernetes it'd be done with a Scheduled pod which does exactly this.
|
Suppose I have a Docker container with Nginx or PostgresQL. I need Cron to delete old log files. Where should I run cron? In the same container inside an entrypoint script? In its onw container? Outside docker?Running in outside Docker will defeat Docker's control over configurations. I will have to use some other configuration management system to pin its config.
|
Should I separate cron into its own docker container?
|
I could not understand what you mean "the first log". Maybe the first line of logs?To run something in the background when SSH connection is closed, I prefer Linuxscreen, a terminal simulation tool that help you run your command in a sub-process. With it, you could choose to view your output any time in the foreground, or leave your process run in the background.Usage (short)screenis not included in most Linux distributions. Install it (Ubuntu):$ sudo apt-get install screenRun your script in the foreground:$ screen python3 my_script.pyYou'll see it running. Now detach from this screen: Press keysCtrl-Afollowed byCtrl-D. You'll be back to your shell where you run previousscreencommand. If you need to switch back to the running context, usescreen -rcommand.This tool supports multiple parallel running process too.Something weirdI've tried to redirectstdoutorstderrto a file with>or>>symbol. It turned out in failure. I am not an expert of this either, and maybe you need to see its manual page. However, I tend to directly write to a file in Python scripts, with some essential output lines on the console.
|
So, I have a python script which outputs some data into terminal from time to time. Im trying to run in on the Ubuntu VPS even after I close the SSH connection and still keep the logs somewhere.Im saving the logs by using:python3 my_script.py >>file.txtand it works perfect, however when I try to run this process usingnohup python3 my_script.py >>file.txt &so it runs in the background and after the ssh connection is closed it seems to save only the first log outputted from my_script.py. I've also tried running this incrontabbut the result is similar - only the first log is saved.Any tips? What am I doing wrong?
|
Ways to run python script in the background on ubuntu VPS and save the logs
|
Thanks for everyone that took the time to answer. So the problem was not with crontab at all but was actually an issue with Python virtual environments. Usingsource activatewas not working with crontab. The solution was to modify the shell script so that it directly uses the Python in the specified virtual environment. For example..#! /bin/bash
cd /home/pi/scripts
/home/pi/berryconda3/envs/myEnv/bin/python pyscript.pyAlso I had logging done within Python but because it crashed early in the script they were never written so I incorrectly assumed the crontab was not executing correctly. I have since discovered that it is a very good idea when working withcrontabto log what's going on directly from cron like this...* * * * * /home/pi/bash/myshell.sh >> /home/pi/logs/cronlog 2>&1This way I could actually see what was going wrong (i.e. Python was throwingModuleNotFoundError).There's a much better answer on this herethat is worth looking at. I'll mark this question as a duplicate.
|
This question already has answers here:Cron and virtualenv(20 answers)Closed4 years ago.Struggling to getcrontabto execute a shell script on my Raspberry Pi. The script runs fine if executed with bash (it's executing a python script that runs in a virtual environment).Here's what I've triedcrontab -e* * * * * /home/pi/bash/myshell.shAnd the shell script...#! /bin/bash
cd /home/pi/projects/scripts
source activate myEnv
python pyscript.py
source deactivateThis works fine...bash /home/pi/bash/myshell.shI also tried editing the root cron tab file directly withsudo nano /etc/crontabbut this also didn't work. What am I missing here?
|
crontab not running shell script [duplicate]
|
You can give timezone to cron by below way."0 5-20 * * * America/Los_Angeles"If you are not sure which timezone will it come just fetch records of timezones of rails with this commandActiveSupport::TimeZone.alland selectTZInfo::DataTimezone.
|
I want to schedule a cron Job to run on 5 AM PST to 8 PM PST? I just want to know how to enforce my job to be run on PST?. I am new to this cron Job.// codecron: "0 5-20 * * *"
|
How to enforce the cron job to run on PST time in rails?
|
You could send the key to the tmux session:tmux send -t session_name ls ENTERif you need to send to a specific panel:tmux send -t session_name.(panelnumber) ls ENTERexample:tmux send -t session_name.0 ls ENTER
|
I want to have more control over a time consuming cron job running on a server. That is, be able to see progress, stop running code if necessary and etc..I thought that this would be possible using a tmux session, but I can not figure out how.I know that you can start new tmux sessions and run code inside it like this:tmux new-session -d -s session_name "some code"I've tried the obvious solution like this:tmux new-session -s session_name
**exit session**
tmux a -t session_name "some code"Is this even possible? Any advice is appreciated.
|
Attach and run script inside an existing tmux session
|
%Iis the hour on a 12-hour clock (intended to be used with%p), so your afternoon files are overwriting the morning ones. Use%Hinstead.
|
I have a rather weird issue. My aim is to use ffmpeg to grab a screenshot from a home CCTV cameras rtsp stream every hour. I want to do this in order to make a timelapse. However everyday from 11am to 12am (the next day) there are no snapshots saved.On an always on Debian machine, this is the shell script I have that crontab calls:dt=$(date +"%d%m%2y%I%M%S")
ffmpeg -rtsp_transport tcp -i "rtsp://IP:554/..." -frames 1 /user/snapshots/ch1/$dt.jpgRunning it by itself works fine and saves a jpg snapshot successfully to the right folders.Incrontab -eI have the following line:0 * * * * /bin/sh //user/snap.shThanks.
|
Crontab task scheduled every hour stops running from 11am to 12am
|
In thecron.yamlthere are unnecessary “-” characters, that are starting the new list.YAML SyntaxCorrect format for Cron Jobscron.yaml,see Google Cloud documentation:cron:
- description: "TEST_TEST_TEST"
url: /cronBatchClean
schedule: every 2 minutesTo deploy Cron Job usegcloud command:$ gcloud app deploy cron.yaml
|
I have the followingcron.yaml:cron:
- description: "TEST_TEST_TEST"
- url: /cronBatchClean
- schedule: every 2 minutesAnd then inapp.yaml:service: environ-flexible
runtime: python
env: flex
entrypoint: gunicorn -b :$PORT main:app
runtime_config:
python_version: 3With this asmain.py:from flask import Flask, request
import sys
app = Flask(__name__)
@app.route('/cronBatchClean')
def cronBatchClean():
print("CRON_CHECK", file=sys.stderr)
return "CRON_CHECK"When I type in the full URL, I receive "CRON_CHECK" on screen but this doesn't seem to be executing. Also in App Engine dashboard, when I click on CRON jobs there aren't any listed.Any help in getting this to execute would be much appreciated,Thanks :)EDIT 1I now have the cron task executing but I'm receiving a404error. When I type the full URL (that is - https://.appspot.com/cronBatchClean) the respective code executes.I added aGEThandler but I'm still not receiving any [email protected]('/cronBatchClean', methods=['GET'])
def cronBatchClean():
print("CRON_JOB_PRINT", file=sys.stderr)
return "CRON_CHECK"
|
Python CRON google flexible app engine not working
|
You could usemarshal.dump(https://docs.python.org/3/library/marshal.html) to save the value when stopping the program, and then loading it viamarshal.loadwhen starting.Honestly, I think it would be a much better approach to fix the root cause of the problem, i.e. solving the exponential run time.
|
I have a program written in python which goes as follows:for i in range(4954):
........
save("/Downloads/pos_" + str(i) + ".h5")The fact is the program running time increases exponentially(we observed it usingtime.time())So what I need is run the program for 10 min and then re run the program.
But I just need to change the i in for loop to the number at which it is stopped.
I can do a cron job, but what should I do to changeivalue?
|
How to repeatedly stop a program after x minutes and re run it changing one variable in python?
|
You must use absolute path for the dataset. Try changing Dataset/file.csv to /cgi-bin/Dataset/file.csv or whatever the absolute path is.
|
The python file begins to get executed but them, error I get is -Time : 2018-12-26 13:00:01.751099
Traceback (most recent call last):File "/home/username/public_html/cgi-bin/pull.py", line 13, in <module>
df = pd.read_csv('Datasets/MC_Master.csv')
File "/home/username/.local/lib/python3.5/site-
packages/pandas/io/parsers.py", line 678, in parser_f
return _read(filepath_or_buffer, kwds)
File "/home/username/.local/lib/python3.5/site-
packages/pandas/io/parsers.py", line 440, in _read
parser = TextFileReader(filepath_or_buffer, **kwds)
File "/home/username/.local/lib/python3.5/site-packages/pandas/io/parsers.py", line 787, in __init__
self._make_engine(self.engine)
File "/home/username/.local/lib/python3.5/site-packages/pandas/io/parsers.py", line 1014, in _make_engine
self._engine = CParserWrapper(self.f, **self.options)
File "/home/username/.local/lib/python3.5/site-packages/pandas/io/parsers.py", line 1708, in __init__
self._reader = parsers.TextReader(src, **kwds)
File "pandas/_libs/parsers.pyx", line 384, in pandas._libs.parsers.TextReader.__cinit__
File "pandas/_libs/parsers.pyx", line 695, in pandas._libs.parsers.TextReader._setup_parser_source
**FileNotFoundError: File b'Datasets/MC_Master.csv' does not exist**The file MC_Master.csv is contained within cgi-bin/DatasetsPS: it works perfectly using shebang command $python3 pull.pywhile i am in thecgi-bin directory.Any guidance would be appreciated.
|
Python script fails to run using a Cronjob but executes from browser
|
Its not only WP, it can happen in any framework. It's more like a generalized question. Here is what I propose you do:Check your error logs. maybe you are having memory limit issues. If its the case, make sure you have memory_limit set something high like 256 or 512M.Put various custom log messages in your function and record it into a separate log file so that you at least know till where it runs and where it stops.Whatever requests you make to external apis like youtube, put it in to a try catch block to catch any exceptions and log them too.Hopefully you will can debug it that way, good luck!
|
So i'm making a plugin that uses the youtube V3 api to bring videos from our youtube channel and turns them into posts for our site.I'm using WP Cron for this. Basically every 12 hours it checks to see if there are any new videos, if there are new videos them it uses the YouTube V3 API to turn them into posts.Everything seems to be working fine except for one thing, which is when WP calls the cron job, the full function does not happen.It should be pulling in about 4 videos. It only pulls in one.Also for some reason the iframes that it puts the videos in inside fo the page don't show up.But when I call the cron job manually using the Cron Manager Plugin
"Advanced Cron Manager" everything works as it should.I can confirm that the function works.I can also confirm that when I tell wordpress to run the cron job that it works.Its only when WP decides to run the cron job by itself that the function does not work. It does run. And it does do some of what the function should do, just not everything.So my question is not so much "why is the youtube api not working" or "why is my cron job not running", But why would a wp cron job work when manually called but not when wp calls it?
|
WP Cron job running but not executing the full function
|
Previously you could setup up Cron jobs using Google App Engine which tigger a PubSub triggered Google Cloud Function, however, this defeated the 'serverless' approach as you are introducing infrastructure to manage and it can take a moderate amount of work to setup the Cron jobs.You can now use the newly releasedGoogle Cloud Schedulerwhich is completely managed, cheap and which makes it very easy to create scheduled jobs via Google PubSub and via HTTP requests. These in turn can trigger the Google Cloud Functions at regular intervals per unit of time or at a specific time of the day/week/month down to a one-minute interval.Note that you are still required to have an App Engine instance in one of the supported regions.
|
How can I easily set up scheduled recurring tasks on Google Cloud Platform to trigger Google Cloud Functions?
|
How can I easily setup scheduled recurring tasks on Google Cloud Platform?
|
Crontab Permissions:There are two files that control the permissions for crontab:/etc/cron.allowand/etc/cron.deny.If there is acron.allowfile, then the user or users that need to use cron will need to be listed in the file. You can usecron.denyto explicitly disallow certain users from using cron.If neither files exist, then only the super user is allowed to run cron.Well, that depends on the system specific configuration to be exact. Most configuration do not allow any users to run jobs, while some systems allow all users to run jobs by default.So, the first step is to create a file namedcron.allowin the/etc/folder. Add the user name to this file in order to allow the user to run jobs.Once the proper permissions has been set, the user should be able to modify and run jobs using thecrontabcommand.
|
I'm trying to run crontab as a user, but any of the scripts won't execute. How I can fix this? Consider that:I tried with BOTHcrontab -eandsudo crontab -u username -e;Scripts are correctly written, since they are executed if I run them
with root crontab;In cron.allow there are both root and user.
|
Crontab won't run for user
|
ERROR: type should be string, got "https://laravel.com/docs/5.7/horizon#deploying-horizonIf you are deploying Horizon to a live server, you should configure a process monitor to monitor thephp artisan horizoncommand and restart it if it quits unexpectedly. When deploying fresh code to your server, you will need to instruct the master Horizon process to terminate so it can be restarted by your process monitor and receive your code changes.Laravel recommends Supervisor for this:[program:horizon]\nprocess_name=%(program_name)s\ncommand=php /home/forge/app.com/artisan horizon\nautostart=true\nautorestart=true\nuser=forge\nredirect_stderr=true\nstdout_logfile=/home/forge/app.com/horizon.log" |
I am just getting started with Laravel and Horizon so I am sorry if my question is a bit out there.I have setup Laravel with Horizon and a Redis database. Everything works fine as long as I have my SSH connection open with thephp artisan horizoncommand running in there. As soon as I close the SSH session, it stops working.I am new with these things so I am wondering what solution there would be. I found someone saying you should dophp artisan horizon &but that seems to work for a few minutes and then nothing.The system is as setup on a webserver so maybe a cronjob can fix it. But my experience with those things is very limited. I hope someone out there can assist.
|
Laravel Horizon stops after I close ssh
|
Withansible 2.6the following is working:- name: "cron"
hosts: localhost
tasks:
- cron:
name: "test"
job: "/bin/true"
minute: "0"
hour: "9"
state: present
disabled: TrueAccording to the documentation, this should work sinceansible 2.0. Important for this to work is, thatdisabled: Trueonly has effect ifstate: presentis set. Acrontab -llists:#Ansible: test
#0 9 * * * /bin/true
|
Is there a way to comment a cron using Ansible?
I tried to usedisablebut it is not working.Playbook:cron: name="server_agent" disabled=yesError message:You must specify 'job' to install a new cron job or variableMy Ansible version is: ansible 2.3.1.0`
|
Does Ansible support comment cron job
|
you can do usingscheduled events, but if you want to use cron and execute every 12 hours, try this$sql = "UPDATE notification SET yes = 1 WHERE yes = 0 and time >= now() - INTERVAL 12 HOUR"
|
I want to run a script after every 12 hour passes of data entry in table.
I used cron job for this.actually i am new to php mysql and i made below query to check if its working or not.so, it is working below is the code.$sql = "UPDATE notification SET yes = 1 WHERE yes = 0 and time >= now() - INTERVAL 1 DAY"this code is working fine for 24 hour but i want it to work for 12 hour and can't understand how to do it.it will be very great if anybody can help me in this problem.
|
How to update row after every 12 hour in PHP MySql?
|
you should paste the full path of script. For example25 11 * * * /home/xxxx/test_script.sh
|
I am trying to set up some cronjobs on Ubuntu for daily tasks. To do so I added for example the line25 11 * * * ~/test_script.shto thesudo crontab -etable. In thetest_script.shI am trying a simple echo to a log file like this:#!/bin/bash
# file: test_script
echo "Test" >> ~/test.logWhen I run the script normally a line with "Test" is added totest.log. However at 11:25 nothing seems to happen. I already checked if the time is set correctly usingecho $(date).What am I missing here?
|
Ubuntu crontab simple echo to file not working
|
You could create a custom command and add it to the crontab.https://symfony.com/doc/current/console.html
|
Is it possible (and what would be the most simple solution), to schedule (like a cronjob) the launch of symfony function ?I would also need to secure it and launch then as anSUPER_ADMIN_USERof my website (using FOSUserBundle).I saw that this is possible to integrate the unix cronjobs (but is there a solution inside symfony ?). Also I could not find information about the rights.
|
Launch Symfony 4 function like a cronjob (as ADMIN)
|
I believe this is what you are looking for:"0 0 0/4 ? * MON-FRI"You can use croneval to check your cron expressions1:$ /usr/share/elasticsearch/bin/x-pack/croneval "0 0 0/4 ? * MON-FRI"
Valid!
Now is [Mon, 20 Aug 2018 13:32:26]
Here are the next 10 times this cron expression will trigger:
1. Mon, 20 Aug 2018 09:00:00
2. Mon, 20 Aug 2018 13:00:00
3. Mon, 20 Aug 2018 17:00:00
4. Mon, 20 Aug 2018 21:00:00
5. Tue, 21 Aug 2018 01:00:00
6. Tue, 21 Aug 2018 05:00:00
7. Tue, 21 Aug 2018 09:00:00
8. Tue, 21 Aug 2018 13:00:00
9. Tue, 21 Aug 2018 17:00:00
10. Tue, 21 Aug 2018 21:00:00For the first expression you'll get following java exception:java.lang.IllegalArgumentException: support for specifying both a day-of-week AND a day-of-month parameter is not implemented.You can also useCrontab guruto get human readable descriptions like:At every minute past every 4th hour from 0 through 23 on every day-of-week from Monday through Friday.
|
I would like my watcher to run from Monday to Friday only. So I'm trying to use this schedule:"trigger": {
"schedule" : { "cron" : "0 0 0/4 * * MON-FRI" }
},
"input": {
...However, I'm gettingError
Watcher: [parse_exception] could not parse [cron] schedulewhen I'm trying to save the watcher. RemovingMON-FRIdoes helps but I need it.This expression works:0 0 0/4 ? * MON-FRIBut I'm not sure I understand why?is required for either theday_of_weekorday_of_monthThank you!
|
How do I create a cron expression running in Kibana on weekday?
|
Lots of options:Add a-Dcron=1command line option when running from cron, to set a property that can be checkedAdd a simple argument to the command line when running from cron and check it by looking in theargs[]arraySet an environment variable in the script and check it in the program.
|
On a Redhat OS, I have a script that launches a Java program. This script can be started from the command line but is launched (periodically) by crontab as well.Within this program, I need to know how the program was started. This because the output is written either to STDOUT (if started from the command line) or in a logfile (if launched by crontab).First I thought I could useSystem.console().The problem is that this method returnsnullalso if the program was started from the command line but with STDIN and/or STDOUT redirected.Any idea how to resolve this?I triedHow can I check if a Java program's input/output streams are connected to a terminal?but that doesn't answer my question.
|
Detect java program started from crontab
|
To debug your environment add this to/etc/crontab* * * * * root env > ~/cronenvWait for file~/cronenvto be created (after a minute) and start a new shell using does environments:env - `cat ~/cronenv` /bin/shThen call your script/usr/local/bin/python3.6 /root/myscript.pyThis will help to test/debug your code within the same environmentcronis using.
|
This question already has answers here:CronJob not running(19 answers)Closed3 years ago.I'm new to freeBSD.
I just set up a server and installed python 3.6.
Now i want to have a python script run every day at 15h00, so i tried to set up a cron task.
But in some way, the cron task never runs or is giving me errors.
Since cron uses mail to report errors and mail doesn't seem to be installed on my server, I have no clue whether the script actually runs or is not running at all.
The line added in /etc/crontab is the following:0 15 * * * root /usr/local/bin/python3.6 /root/myscript.pyWhere /usr/local/bin is the directory where python is installed.
When running this command in the normal command line, it works perfectly, but with cron, it keeps not working.
Any help is welcomeThanks in advance
|
Running a python script as a cron job in FreeBSD [duplicate]
|
Try like this to set crontab using root user,sudo crontab -eDo your changes viananoorvim. Finally save and quit* */2 * * * /var/www/html/script.php
* */2 * * * root /var/www/html/script.phpNo needto restart again using thissudo /etc/init.d/cron restart
|
I want to setup a cronjob for PHP script in ubuntuI enter this command in terminal$ crontab -eThen I choose nano editor which is recommended by ubuntu. Then I enter the blow line into that. Then I press control+C, it asking Y/N for save. I press Y and F2 for close.* */2 * * * root php /var/www/html/script.phpOther things I've tried:* */2 * * * /var/www/html/script.php
* */2 * * * root /var/www/html/script.phpAfter that, I restart cron using the below command.sudo /etc/init.d/cron restartThen I check crontab list usingcrontab -l, it says no cron job set for the root user.I tried to directly create a crontab.txt file into the cron.hourly / cron.d directory with one of the above line.I tried numerous forum and all sayscrontab -ethen enter or create crontab file inside cron directory. Nothing is helping me. I am scratching my head.What is the correct way to create cronjob for php script in ubuntu 16.04 & php version 7.0
|
Setup a cronjob for PHP script in ubuntu & PHP
|
I am under the assumption that the log file is created using redirections. So I would suggest the following approach:# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7)
# | | | | |
# * * * * * command to be executed
* * * * * mkdir -p `date "+/logdir/\%Y/\%m/\%d"` && command > `date +/logdir/\%Y/\%m/\%d/result_\%dd_\%mm_\%Y_\%Hh_\%Mmin_\%Ssec` 2>&1The commandmkdir -p dir1/dir2/dir3will create every directory and subdirectory needed. In this case it will be/logdir/YYYY/MM/DD
|
I have crontab job running every minute. This cron job logs to/tmp/result_"`date +\%dd_\%mm_\%Y_\%Hh_\%Mmin_\%Ssec`".logHow to make the cron job store logs by folders is following way:create folder if not exist foryear( named by year,like 2018)inyearfolder create(if not exist)monthfolder (likemarchor month number)in month folder,if not exist create day folder (day number)and then: store log for each minute in specific day folder.Also for now i have my logs written everyminute to /tmp/*, i have many log files like thisresult_04d_03m_2018_20h_39min_01sec.logHow parse all this files and depending on its names create, for each year/each month/ each day/ folders and move specific logs to its folder?
|
How to create folder(if not exists) for crontab logs, and write log to specific folder depending on date?
|
cron will execute the script using a very stripped environment. you probably want to add the full path to the mysql command to the cron scriptyou can find the full path bywhich mysqlat the prompt,
or you can add an expanded path to the cron invocation1 2 * * * PATH=/usr/local/bin:$PATH scriptname
|
Im using a bash script (sync.sh), used by cron, that is supposed to sync a file to a MySQL database. It works by copying a file from automatically uploaded location, parse it by calling SQL script which calls other MySQL internally stored scripts, and at the end emails a report text file as an attachment.But, seems like something is not working as nothing happens to MySQL databases. All other commands are executed (first line and last line: copy initial file and e-mail sending).
MySQL command when run separately works perfectly.
Server is Ubuntu 16.04.
Cron job is run as root user and script is part of crontab for root user.Here is the script:#!/bin/bash
cp -u /home/admin/web/mydomain.com/public_html/dailyxchng/warehouse.txt /var/lib/mysql-files
mysql_pwd=syncit4321
cd /home/admin/web/mydomain.com/sync
mysql -u sync -p$mysql_pwd --database=database_name -e "call sp_sync_report();" > results.txt
echo "<h2>Report date $(date '+%d/%m/%Y %H:%M:%S')</h2><br/><br/> <strong>results.txt</strong> is an attached file which contains sync report." | mutt -e "set content_type=text/html" -s "Report date $(date '+%d/%m/%Y %H:%M:%S')" -a results.txt --[email protected]
|
What is wrong with this bash script (cron + mysql)
|
The easiest solution is to sleep for 10 seconds:# .----------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7)
# | | | | |
# * * * * * command to be executed
31 10 * * 3 sleep 10 && /file/to/run.py
|
I would like to run a cron job every Wednesday at 10:31:10, but I just learned that crontab cannot run sub-minute jobs, so the closest I can get is 10:31 a.m. with the below code:31 10 * * WED /file/to/run.pyIs it possible to hack around this, or are there other alternatives to cron that could do the job?
|
How can I run sub-minute cron jobs?
|
A cronjob runs in a limited environment under/bin/sh. What is probably happening is that the default core-dump size is set to zero.
I do believe that this can be seen and configured in/etc/security/limits.conf, however the easiest way to check this is to run the following cronjob :* * * * * ulimit -a > ~/cron.ulimit.txtIf the file~/cron.ulimit.txtindicates a core-file size ofzero blocks, then the cron-job will never generate a core file.You can create a core file by running a wrapper scriptwrapperwhich sets the ulimit for the core-file size. Eg.#!/usr/bin/env bash
ulimit -c unlimited
/path/to/binaryThis script can then be ran as a cronjob.
|
I'm running Ubuntu 15.04 on a MicroZed where I'm executing a program that dereferences a null pointer from a crontab script. Note: I am purposefully trying to create a core dump.The issue is that when I run the program from the command line the core dump is generated as expected, however when running from the crontab I can't locate the file in any of the expected locations.Any ideas on whether or not the core dump is actually being created, and if so where?
|
crontab core dump not generated?
|
In the SilverStripe 3 version of Fluent you can useFluent::with_localeto perform a callback under the context of a given locale, e.g.:Fluent::with_locale('de_DE', function () {
$myObject = MyObject::create();
$myObject->Title = 'German title';
$myObject->write();
});For reference, in the SilverStripe 4 version you can do this instead:FluentState::singleton()->withState(function (FluentState $newState) {
$newState->setLocale('de_DE');
// ...
});
|
Good afternoon,Does somebody know if there is a method to set locale manual? I want to update some locale based items in the database by a cronjob, but to make it work I have to set locale based on some variables instead of the locale of the server.
|
Silverstripe fluent set locale
|
You have to make a shell script which will do the steps of changing to script directory, activating virtual environment and then running it.Example:#!/bin/bash
cd $YOUR_DIR
. venv/bin/activate
python3.4 test.pyThen you call this script in cron with/bin/bash /.../script.shWhat you could do additionally ischmod +x test.pyand add/update first line to:#!/usr/bin/env python3.4This way you can just run Python script with./test.py
|
I tried to make a cron job on crontab which runs a python script on AWS ec2. My python script includes a module that is only available for python3.
Using the following command I changed the ec2 default python interpreter from python2.7 to python3.4
Source /home/ec-2user/venv/python34/bin/activate
and then using pip install, I installed the required module for python3.4. So now the default interpreter is python3.4 and when I run the script on ec2-user directory using the following command:
python test.py
the program runs without any problem (so I am sure the module is installed correctly).
But when I assign python file to a cronjob
* * * * * python test.pyIt does not work. Checking the mail, the error is:
“No module found named “xxxxx” “But as I said it worked fine outside of the cron.I was wondering if you can help me with this problem. I appreciate your time and information.
|
Cron does not execute a python script that needs a python3 module in AWS-ec2
|
Use| xargs echoto append the newline.Your entry would look something like this:0 0 * * */1 wget -t 1 - "http://urlto.job/job9" -O - | xargs echo >> home/password_reset_log.txtOf course, this will only work if your URL always gives exactly one line each time.Here the demo for everyone to enjoy:user@host:~$ echo -n "No newline"
No newlineuser@host:~$ echo -n "With newline" | xargs echo
With newline
user@host:~$
|
So I am trying to create a cron job that will, on a daily basis, execute a job on a webpage.My cron command:
0 0 * * */1 wget -t 1 - "http://urlto.job/job9" -O ->> home/password_reset_log.txtAll of this works, however I am trying to carry out the seemingly menial task of adding a new line to each entry in the text file.Currently I get:{"error":0,"result":"Password reset email successfully sent to 0 users, 0 emails failed to send","jDateLastRun":"10 Jan 2018, 00:00:07","jHandle":"check_password_resets","jID":"9"}{"error":0,"result":"Password reset email successfully sent to 0 users, 0 emails failed to send","jDateLastRun":"10 Jan 2018, 00:00:07","jHandle":"check_password_resets","jID":"9"}So all the entries are on a single line. What I want is:{"error":0,"result":"Password reset email successfully sent to 0 users, 0 emails failed to send","jDateLastRun":"10 Jan 2018, 00:00:07","jHandle":"check_password_resets","jID":"9"}
{"error":0,"result":"Password reset email successfully sent to 0 users, 0 emails failed to send","jDateLastRun":"10 Jan 2018, 00:00:07","jHandle":"check_password_resets","jID":"9"}So all the entries start on a new line (easier to read and see which jobs ran successfully and which failed and the result of each time the job ran).Is there a simple way to do this (perhaps adding a parameter to my cron command).
|
cron & wget adding new line to each document write
|
You can't because controllers are bound to HTTP.However, you can refactor your code and extract the email sending logic to a mailer, and call that mailer from both your controller and your rake task.
|
So a bunch of mailing methods in Article controller, that mix different types of articles with different users. All work fine when called from somewhere within Rails. But they need to be executed during the week by cron. What goes in place of "xxxx" in the rake file to tell it to execute the "10_am_action" method in the Article controller?articles_controller.rb:def 10_am_action
[sends the right e-mails to the right users]
endCron:0 10 * * 0 cd /data/website/current && RAILS_ENV=production bundle exec rake emails:10_amemails.rake:namespace :briefings do
desc "10 am e-mails"
task :10_am => :environment do
xxxxxx
end
end
|
Rails: how do you tell cron to execute a controller method?
|
This is a shot in the dark, but make sure you are starting a database connection in your CRON job. Otherwise you won't be able to execute any queries.
|
I'm having this weird situation where my Cron Job is successfully executing a function that returns a promise, however, when it tries to execute a.find()on the Model, it never actually executes. I have this same function used elsewhere in my app and is called via an API call and returns no problem. Is there something I'm missing?Here is my cron script:var CronJob = require('node-cron');
var TradeService = require('../services/TradeService');
// Setup the cron job to fire every second
CronJob.schedule('* * * * * *', function() {
console.log('You will see this message every second');
TradeService.executePendingTrades();
}, null, true, 'America/Los_Angeles');Here are the related functions that get called:exports.executePendingTrades = () => {
// Get all pending trades
exports.getPendingTrades().then(results => {
console.log('results', results); // This never fires
})
}
exports.getPendingTrades = () => {
return new Promise((resolve, reject) => {
Trades.find({})
.where('is_canceled').equals('false')
.where('is_completed').equals('false')
.sort('-created_at')
.exec( (err, payload) => {
if (err) {
return reject(err); // This never fires
}
return resolve(payload); // This never fires
})
});
}
|
NodeJS cron job - Mongoose won't execute a .find on a model via a function called in a cron tab
|
Well, I assume you use the r-base image. If you just need your R script to run in the currently existing container, just create a new cron entry in your host using thedocker execcommand.Example* * * * * docker exec -it $instanceName Rscript yourScript.R
|
I installed rstudio on aws lightsail following byhttps://jrfarrer.github.io/r/2016/12/29/RStudio-Lightsail.html.Now i am trying to run rscript every minute using by crontab or anything that run rscript regularly.Thank you in advance
|
How to set up to run r script on docker image using crontab
|
It depends on what your exact Javascript needs are, but unfortunately, if your application truly depends on a browser (and can't be ported to something more appropriate for the constraint), you will need to "fake" the browser somehow. Here are a few options.PhantomJSis basically a headless Webkit engine (think Chrome or Safari).HtmlUnitfor a Java based solution, supported/developed by MozillaOther rabbit holes(Wikipedia/Headless Browser)NodeJSoffers a non-browser, headless, Javascript specific option, but will require your code to be more robust and generic than many code bases initially are when originally coded for browsers.
|
I have an application that I need to deploy that is a mix of pure PHP, JavaScript, jQuery, and AJAX. It runs flawlessly on all machines when called in a browser. Unfortunately, I also need to deploy this application to a machine that won't be able to run a browser.Just running the file using PHP will output the resulting file, but does not execute any of the Javascript.What are my options to get this task running? The machine will have access to xampp, but not to a browser.Edit: the application grabs data from MSSQL, uses Javascript to turn that data into charts, uses an AJAX call to save those files to disk, and then calls another PHP script to mail a copy of the resulting files.
|
Run PHP/Javascript/AJAX Application On Schedule/Cron?
|
To paste a multi-line bash code into terminal, add parenthesis around the lines otherwise each line gets run as a separate command as soon as it gets pasted:(df -h | nawk '/backup/ {print $5 " " $6}' | while read line; do
usep=$(echo "$line" | nawk '{printf "%d", $1}')
partition=$(echo $line | nawk '{print $2}')
if(("$usep" >= 90)) ; then echo "$partition ($usep%)" | mailx -s "172.27.68.101"[email protected];
echo "$partition ($usep%)" | mailx -s "172.27.68.101"[email protected];
echo "$partition ($usep%)" | mailx -s "172.27.68.101"[email protected];
fi
done)
|
I have written following script and it shows some unnecessary files when i'm running it. I just want to execute only the command and receive the alerts only.
the script as followsdf -h | nawk '/backup/ {print $5 " " $6}' | while read line;
do
usep=$(echo $line | nawk '{printf "%d", $1}' )
partition=$(echo $line | nawk '{print $2}')
if (( $usep >= 90)); then
echo "$partition ($usep%)" | mailx -s "172.27.68.101"[email protected];
echo "$partition ($usep%)" | mailx -s "172.27.68.101"[email protected];
echo "$partition ($usep%)" | mailx -s "172.27.68.101"[email protected];
fi
doneFollwing image shows the output problemHow can i add multiple recipient to this script without opening such directories?
|
Linux script shows unnecessary files
|
At first I suspected that CVS run from crontab couldn't findrshdue to difference inPATHvariable in login shell and incronenvironment.I was wrong, the answer is to setCVS_RSHtosshin script run from crontab, as original author figured out. This is because CVS being really old defaults torshas remote shell. But asrshisn't secure, probably most administrators of CVS repositories require connection with a secure shell,ssh.Credit goes to:https://bugs.archlinux.org/task/12636#comment42630
|
I've made a sh script for update my work directory every night:20 20 * * * /home/oracle/scripts/lancia_script.ksh /home/oracle/setORACLE_ENV /home/oracle/scripts/update_cvs.ksh > /home/oracle/logs/crontab/update_cvs.log 2>&1file update_cvs.ksh:[...]
cd $CVSDIR
cvs update
cd -
cp -R $CVSDIR/* $SCRIPTSDIR/
chmod 744 $SCRIPTSDIR/*.ksh
[...]If I run it manually there aren't problems, but if I schedule it I recived:cvs [update aborted]: cannot exec rsh: No such file or directory
cvs [update aborted]: end of file from server (consult above messages if any) /u01/home/oracleWhy?
|
CVS update in crontab
|
flock -n LOCK-FILE COMMANDIn your case:-n: if flock cannot obtain the LOCK-FILE, i.e. it already exists, it will stop right there, and not execute the COMMAND.So the -n ensures only one instance of COMMAND can run at a time.in your case LOCK-FILE is /var/www/vhosts/SOMEDOMAIN/scripts/blia_bab_import.sh.lockThe LOCK-FILE is what you decide it to be. flock will check for that file as a lock. It could be named anything, anywhere on your system, but doing it this way is nice since you know what the .lock file is used for.To illustrate, you could do flock -n /tmp/some_lock_file.txt script.sh. The value is not enforced, you decide what you want to use.COMMAND in your case is /bin/bash /var/www/vhosts/SOMEDOMAIN/scripts/blia_bab_import.shThe script you want to execute is the value of COMMAND, so again for you: /bin/bash /var/www/vhosts/SOMEDOMAIN/scripts/blia_bab_import.sh/bin/bash is to specify that the script blia_bab_import.sh must run inside a bash shell. You could do without by using the #!/bin/bash first line in your .sh file.
|
I have this cronjob, that is not working for some reason, but I don't entirely understand what it does, could someone explain?flock -n /var/www/vhosts/SOMEDOMAIN/scripts/blia_bab_import.sh.lock /bin/bash /var/www/vhosts/SOMEDOMAIN/scripts/blia_bab_import.shI googled that flock is supposed to lock the file and only run if it can lock the file, so that the job cannot run multiple times at the same time.What does the -n do?flock -nWhy is this a .lock file?/var/www/vhosts/SOMEDOMAIN/scripts/blia_bab_import.sh.lockI have no idea what the /bin/bash is supposed to do?/bin/bashIs this the script I want to execute?
Why is it added as a .lock first?/var/www/vhosts/SOMEDOMAIN/scripts/blia_bab_import.sh
|
Need specific cron job explained that uses flock -n + .lock file + /bin/bash
|
In order to see the possible errors, add an output file.Something like this* * * * * php /var/www/html/ngix/hotshoponline.com/api/artisan schedule:run > /var/log/error.log 2>&1Then tail the error.log file to see if there are errors.tail -f /var/log/error.log
|
I have php script ran by cron. When I manually runphp /var/www/html/ngix/hotshoponline.com/api/artisan schedule:runit works fine, the script takes about 2 mins, and I can get the output I need.But when it's called by cron like this* * * * * php /var/www/html/ngix/hotshoponline.com/api/artisan schedule:run >> /dev/null 2>&1it is not working
i tried with -f and tried with /usr/bin/php nothing is working
|
PHP script is not exceuted by laravel cron
|
Does your app use gunicorn?gunicorn will by default use synchronised workers and kill them after 30 seconds.
On my Google App Engine app, it killed everything after 30 seconds regardless of if it's a cloud task or cron job.2 possible ways to get around it are:Use Async workers, see here:How can I run long tasks on Google App Engine, which uses gunicorn?, I haven't tried it.Or change the timeout for the synchronised workers, here is my app.yaml '--timeout=600' sets the gunicorn worker timeout.
This is for a Google App Engine Python 3 Standard App.runtime: python37
entrypoint: gunicorn -b :$PORT main:app --workers=4 --timeout=600
instance_class: B8
basic_scaling:
max_instances: 11
idle_timeout: 10m
runtime_config:
python_version: 3
handlers:
- url: '/.*'
script: auto
|
I am trying to schedule a task on app engine using cron that will run continuously on background. I have written the cron task it works fine on local server but when I run it through google cloud console it failed after 30 seconds.cron.yaml:cron:
- description: daily tweets streaming
url: /path/to/cron
schedule: every 24 hoursviews.py:def testing(request):
print("okasha---")
from streamTweets import start_stream
start_stream()urls.py:url(r'^path/to/cron$', views.testing, name="testing"),I have read a solution that says to divide the task into subtasks but i am not able to divide it into subtasks. My log says No entries found but when I access it directly by url it starts the script but after 30 seconds it gives 502 bad gateway error.
|
Google app engine cron django failed after 30 seconds
|
I'm not familiar with cPanel, so I can't address that aspect of the question, but, from the Perl side, I can tell you that deleting the cron job will do no (additional?) harm. Because there's a syntax error in the Perl code, the checkupdates program is already not running (and, indeed,can'trun).Checking with any appropriate vendor to see whether they can provide a fixed copy ofCpanel::JS::Variations(the source library which contains the actual error) would likely be a good idea, as it may be used by other pieces of Cpanel which actually are important, but the cron job isn't doing anything other than generating email to tell you it failed.
|
One of the automatically generated cron jobs, namely:2 0 * * * /usr/local/bin/perl /usr/local/cpanel/3rdparty/quickinstall/scripts/checkupdates.ploutputs this:Bareword found where operator expected at /usr/local/cpanel/Cpanel/JS/Variations.pm line 20, near "$filename =~ s{/js2"
(Might be a runaway multi-line // string starting on line 19)
(Missing operator before js2?)
syntax error at /usr/local/cpanel/Cpanel/JS/Variations.pm line 20, near "$filename =~ s{/js2"
Global symbol "$filename" requires explicit package name at /usr/local/cpanel/Cpanel/JS/Variations.pm line 21.and many other errors.Would it be safe to delete this cron job? especially considering that:it is faulty in the first place;I don't have access to the Perl script in question and can't fix it;quickinstall modules (such as WP and Moodle) properly check for updates themselves.I'm using a shared hosting on HostGator and, as such, don't have a shell access; all I can do is work thru cPanel.
|
Faulty cron job: safe to delete?
|
if you want to add your project's cron jobs in crontab, just add them in crontab file:change editor to nano (optional)setenv EDITOR nanoopen crontab filecrontab -eadd this line* * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1replacepath-to-your-projectwith the real path and the cron will be executed automatically.
If this doesn't work, replacephpwith full php path. To find the whole path just type in command linewhich php.For more info read thedocs
|
I have acronjobwith namechangeflag. I can use following terminal command to execute thiscronjobin local.php artisan changeflagIn hosting server, I can easily set the execution of console command with cron job.Is it possible to run above command periodically in local system in Linux automatically as in server ?orWe have to execute above command through terminal for every test ?I am usingLAMP.Any help is appreciated.
|
How to run laravel cronjob in local linux system?
|
I find my mistake, i make a mistake in the path of Perl :
/sw/freetools/perl/5.8.8/Linux/rh6/x86_64/bin/perl/sw/freetools/perl/5.8.8/Linux/rh60/x86_64/bin/perlThank you for your help.
|
I want to execute a Perl script every two minutes.This script sends me an email that contains files. It works fine manually.I tried in a crontab*/2 * * * * /sw/freetools/perl/5.8.8/Linux/rh6/x86_64/bin/perl /home/httpldev/iLicoMetrics/metrique.pl &> /dev/nullI also tried with*/2 * * * * /home/httpldev/iLicoMetrics/metrique.pl &> /dev/nullbut I got no output.
|
No output from script run under crontab
|
You may do it like soIn thecrontab*/1 * * * * /usr/bin/php -d memory_limit=-1 -d max_execution_time=0 /home/mywebsite.com/215a/applications/core/interface/task/task.php 8222157ad26eg58q51dh343ha7j472az==========================================================Alternatively, you may put the command in ashell scriptand execute the shell script.command.sh#!/bin/sh
/usr/bin/php -d memory_limit=-1 -d max_execution_time=0 /home/mywebsite.com/215a/applications/core/interface/task/task.php 8222157ad26eg58q51dh343ha7j472azMake sure to make the shell script file executable$chmod a+x command.shThen in thecrontab*/1 * * * * /path/to/command.sh============OR=============Without making the shell script file executableIn thecrontab*/1 * * * * /bin/sh /path/to/command.sh
|
So I've been looking up cronjobs for the past few minutes... I have a general sense of how to add one to my websites ubuntu system.... I need to make my system run a corn job once a minute (according to the software I'm having it use).First I log in via SSH..Then I enter root mode.Then I type crontab -eThen each line is a scheduled cron job....The instructions on the softwares site says to just run the following command once a minute:/usr/bin/php -d memory_limit=-1 -d max_execution_time=0 /home/mywebsite.com/215a/applications/core/interface/task/task.php 8222157ad26eg58q51dh343ha7j472azI know that the start of the crontab line should read like this:*/1 * * * * /path/to/commandMy confusion is this.... Can I just put the instructed command in the /path/to/command part, or do I need to create a file and put the files address there? Also if I have to make a file, what format?
|
How do I write a cronjob?
|
Need to setup messaging for that.It’s common to use a persistent queue such as RabbitMQ. The microservice responsible for sending emails then consumes the messages from the queue and handles them appropriately.If you run into a problem of your single instance of email microservice not being enough you can simply fork another instance and deploy it instantly. This is because when a message from the message queue is consumed it’s gone unless you tell it to return (to be requeued). I.e. any successfully sent email will consume the the message hence the request to send an email is no longer within the system.
|
For example I want to have a microservice to send notifications(email, sms, push notification). Everything is ok for few users. After some time our application have a lot of users, so, this microservice doe not manage, and email a sent after 1 hour.So, how to handle this situation? Deploy another instance of microservice, but how to handle that only one microservice process one email and user don't receive multiple emails?
|
Microservices for job/cron tasks
|
That sounds like your cron job is only runningartisan schedule:runonce per day. Make sure your cron job is set up like the docs:* * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1The* * * * *part means run every minute, and then Laravel will decide which tasks to run each minute based on your schedule.
|
I am using LaravelTask SchedulingI need to run multiple tasks at different times, like this:protected function schedule(Schedule $schedule) {
$schedule->call('App\Http\Controllers\SomeController@job1')->daily();
$schedule->call('App\Scheduled\SomeClass@job2')->hourly();
$schedule->call('App\Scheduled\SomeClass@job3')->hourly();
$schedule->call('App\Scheduled\SomeOtherClass@job4')->daily();
}But for some reason everything runs once a day (at 12:00am). What am I doing wrong?
|
Laravel Scheduling conflicts with multiple calls
|
Since the first Monday of the month is always within the first seven days of the month, you can use this:1 9 1-7 * 1
|
I googled for help couldn't find help myself so asking a quick question on cron schedule with Hangfire.How to set cron expression if I want to execute hangfire recurring job every first monday of every month?The expression 1 9 * 1/1 1#1 does not work in hangfire (as it uses crontab syntax and 1#1 is throws exception.I'm using CronGen fromhereand modifying it to generate CronTab syntax valid for Hangfire.
|
Hangfire recurring job for Every first Monday of month
|
curl ... && [ -s ~/list/json.tmp ] && cp ~/list/json.tmp /srv/www/list.jsonThe-stest is true if the named file exists and is not empty.(Incidentally, the> /dev/nullredirection is not necessary. Thecpcommand might print error messages to stderr, but it shouldn't print anything to stdout, which is what you're redirecting.)
|
I have a cronjob getting a list of prices from a website in JSON format and copying it into the right folder and it looks like this:curl 'https://somesite.web/api/list.json' > ~/list.json.tmp && cp ~/list.json.tmp /srv/www/list.json > /dev/nullThe problem is that a couple of times the website was down while the cron was trying to get the list and got an empty JSON file. To prevent this in the future, is there a way to make the cron only copy the file if it's not empty (no cp option to do this)? or should I create a script to do that and call the script after getting the list?
|
Ubuntu command to copy file only if origin is not empty
|
I fixed this by replacingRscriptin my crontab with/usr/local/bin/Rscript(or wherever your Rscript is located - dowhich Rscriptto find out).
|
I'm trying to setup a Cron job on my system by adding the following line17 12 * * * Rscript ~/path/to/file/script.R > ~/output_`date +\%d\%m\%y`.txt 2>&1yet, I cannot see the file the output is being written to. I've consulted the following answers, but to no avail:Why did my crontab not triggerCronJob not runningWhen I run the following command on the terminal:Rscript ~/path/to/file/script.R > ~/output_`date +\%d\%m\%y`.txt 2>&1I get the output file as expected. I also added the following line to crontab:* * * * * echo hi > ~/output.txt 2>&1and it works just fine. I'm not sure what is wrong with the first command. Any help would be appreciated. Thanks.
|
Crontab doesn't execute R script
|
You can check the current hour inside theonTick:onTick : function() {
// Don't do anything if between the hours of 12AM and 6AM.
if (new Date().getHours() < 6) return;
// The job code follows:
},
|
I need some help in setting up a cron server in which the process will run every two minutes, but stop at 12am and restart running every two minutes at 6 am.I have already set up it to run every two minutes. Any help please ?new cronJob({
cronTime: '0 */2 * * * *',
onTick: function() {
//process run after every two minutes
},
start: true
});
|
NodeJs: Setting up cron server every 2 minutes but stop it in between 12am to 6 am?
|
It likely fails becausePATHis not set. You should set the PATH in theMakefileand export it:PATH := /usr/bin:/usr/local/bin:/some/other/dir
export PATHYou can test your command by specifying a very limited environment:/usr/bin/env -i PATH=directorylist_here HOME=$HOME your_cron_cmdPS: Usually any output on stdout and stderr is mailed to you by cron. Did you check your inbox for cron mails? These may provide additional clues.
The mails are sent to the mailbox of the user the crontab belongs to. So if this is run as root it will be in root's inbox. (Of course this will work only if stdin+stdout weren't redirected to/dev/null). On a Unix system, you can read the inbox mails with themailor maybemailxcommands.
|
I am trying to run a make file from within cron. My command is pretty simple:* * * * * /usr/bin/make -C "/home/path_to_file/" -f "/home/path_to_file/Makefile"It runs normally in the shell, but it fails in the crontab.How can I debug this kind of problem?Any suggestions what might be my error?
|
Gnumake in crontab
|
You need to change your if to:if [ "${cron}" -eq 0 ]Seehttps://stackoverflow.com/a/18161265/7581259
|
I'm pretty new to this bash scripting, but looking forward to learn a lot more about it. But I'm stuck here where I'm trying to only make the script to do theprintfif the value ofcron=0else nothing, but continue the script. I'll get an error on the line "then printf" and the script fails if i change the cron value to anything but0cron=0
if ! [ -w ${dest_dir} ]
then
if (${cron} == 0)
then printf "%s\n" "Eureka! ${dest_dir} is write protected!!"
fi
else
exit 1
fiSomeone who could tell me what's wrong and give me a push in the right direction?Update 1Do to my question of clever bash guys I got this lovely quick answer [ "$value" = x ] && exec >/dev/null 2>&1 will redirect both stdout and stderr to /dev/null if your value is x (per a string comparison, as opposed to a numeric comparison).Unfortunately I do not quite understand how to use that I practice to hoping for a little real example vs my scriptSo how should I implement it into this#If value cron=0 do printf, if value cron=1 do not printf
cron=0
if ! [ -w "${dest_dir}" ]
then
if [ "${cron}" -eq 0 ]
then
printf "%s\n" "Eureka! ${dest_dir} is write protected!!"
fi
else
exit 1
fi
for i in "${FILES[@]}"
do
file=${dest_dir}"$i"
if [ -f "${file}" ]
then
if ! [[ -w "${file}" ]] ; then
printf "%s\n" "'${file}' is write protected!!"
exit 1
fi
fi
done
|
Bash only printf if cron = 0
|
You can useNode Cron, it is a Node package that allows you to schedule tasks.In this case, you could check every day if each post was created more than 7 days ago (or the time expiration the user set), and if it is, delete it.This is thepackage repowith the documentation of how to use it:Node Cron by merenciaI hope it helps you!
|
I'm building a website using MEAN stack. A user will post an item (and it will be stored to MongoDB) and I want to implement an expiry on that post. For example, they choose 7 days, after 7 days the user's post will be closed. How can I achieve that? It's like it will run a function to close the post based on how long the user sets it. I can't imagine how will I achieve it.How can I implement something that will automatically close the post of a user based on the days they set?
|
NodeJS - Expiration on posts
|
You should configure your TaskScheduler thread pool size. if you are not configure, the default size is 1 which is mean spring will execute your task one by one. You can configure your TaskScheduler below.@Configuration
@EnableAsync
@EnableScheduling
public class SpringBootConfiguration {
@Bean
public Executor getTaskExecutor() {
return Executors.newScheduledThreadPool(10);
}
}
|
I want to schedules multiple task using@scheduleannotation using cron expression. I have three job which require to execute at fixed time. For example,Job-1 has been schedule every day at 11:PM, Job-2 has been scheduled every day 7AM-9PM in 1 hour interval and Job-3 has been schedule in every 1 hour. All the 3 schedule tasks are part of the same application.I have tried the same but all three scheduling is not happening. My application isSpringBoot application.I am not new scheduling.Kindly help me out. Below is he my approachapplication.propertiescron.expression.job1=0 0 23 * * ?
cron.expression.job2=0 0 7,9 * * ?
cron.expression.job3=0 0/60 * * ?Java Code@EnableScheduling
@SpringBootApplication
public class Scheduler{
// doCallScheduleJob Code
}
class ScheduleJob{
@Scheduled(cron="${cron.expression.job1}")
public sycName1(){
///doSomething()
}
@Scheduled(cron="${cron.expression.job2}")
public sycName2(){
///doSomething()
}
@Scheduled(cron="${cron.expression.job3}")
public sycName3(){
///doSomething()
}
|
How to scheduling multiple task through cron expression using Springboot?
|
Cron jobs start with a very limited set of environment variables.
There's likely one or more environment variables you get from your ~/.profile or ~/.login (or the like).Try moving the whole job into a script and invoke it like this:22 * * * * /home/work/ui/mycronjobInmycronjobyou'd have something like this:#!/bin/bash
source ~/.bash_profile
cd /home/work/ui && /home/work/.jumbo/bin/python test.py >> result.logThat assumes your $SHELL is bash and you have a ~/.bash_profile.
If you have some other shell or other init file (~/.login, ~/.profile, etc) use that instead.
|
I have the following crontab:22 * * * * cd /home/work/ui && /home/work/.jumbo/bin/python test.py >> result.log &And thetest.pyhave the following codes:#!/home/work/.jumbo/bin/python
#coding=utf-8
import datetime
import hashlib
import logging
import os
import Queue
import signal
import sys
import threading
import time
import traceback
#注释
if __name__ == "__main__":
print 'Begin'
print 'End'OK, the codes can run right, but I addimport requestsafter, it will not run right, I think that it can not find lib path.So, I usesys.path.append, but it still can not run right.#!/home/work/.jumbo/bin/python
#coding=utf-8
import datetime
import hashlib
import logging
import os
import Queue
import signal
import sys
import threading
import time
import traceback
sys.path.append('/home/work/.jumbo/lib/python2.7/site-packages/requests')
print sys.path
import requests
#注释
if __name__ == "__main__":
print 'Begin'
print 'End'And then, how do I it?BTW, I can run it right on OS command.So my code is OK.
|
Crontab can not run Python script because the python file have third-party lib
|
Is there a way to implement scheduling inside Rails without using Cron
or a better way of managing regular tasks that works well with Rails?Cron is pretty much the go to tool for running scheduled activities on *nix system and most gems actually leverage cron under the hood, in fact avoiding cron is probably a lot more work unless you want to use a third party service.One of the new features of Rails 5 isActiveJob:Active Job is a framework for declaring jobs and making them run on a
variety of queuing backends. These jobs can be everything from
regularly scheduled clean-ups, to billing charges, to mailings.
Anything that can be chopped up into small units of work and run in
parallel, really.It can be used with several backends:SidekiqResqueSucker PunchQueue Classic
|
I'm new to Rails so I'm not sure if this is a stupid question but...I have to run regular tasks to populate data to my Rails app. Today I use the whenever gem to create Cron entries to run these tasks on my system. I want to migrate my Rails app to Docker so that I can scale it more easily. I know that in Drupal(PHP) there is Poorman's Cron which uses requests to drive schedules.Is there a way to implement scheduling inside Rails without using Cron or a better way of managing regular tasks that works well with Rails?
|
Rails 5 Regular Tasks Without Cron
|
If you start script with cron always use full path of file.Add to every path in your scriptdirname(__FILE__)and add/if necessary.
|
I have a PHP script that reads email, saves the attachments, read the saved csv files and load a DB with the content of the csv files.
I use the Jamesiarmes\PhpEws library to connect to my Exchange Server and all is working perfectly.
As I need to do it every day, I use crontab to run the PHP script every day at ten o'clock.00 10 * * * /usr/bin/php /home/web/update/format-recent-report.php > /home/web/log/readmail.log 2> /home/web/log/readmail.errThe problem arises when Crontab tries to run the script. The readmail.err file contains the following error:PHP Fatal error: Class 'jamesiarmes\PhpEws\Client' not found in
/home/web/update/exchange_config.php on line 8Here it is theexchange_config.php:<?php
use \jamesiarmes\PhpEws\Client;
$host = 'xxx.xxxx.it';
$username = 'yyyyy';
$password = 'zzzzzz';
$version = Client::VERSION_2010;
?>Afetr getting the error, I go to the directory where the script is located and try to run the script manually with:php format-recent-report.php > logand the script works correctly. Why this difference between crontab and manual ?I don't post the content of the PHP script because it is very long, but I can say that it starts with:include '../vendor/autoload.php';
include 'exchange_config.php';it stops at the very beginning.
|
PHP Classes not found with crontab
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.