Response
stringlengths 8
2k
| Instruction
stringlengths 18
2k
| Prompt
stringlengths 14
160
|
---|---|---|
One approach would be to make sure that if those two jobs are separate cron jobs - there is enough time inbetween to surely cover the run of job 1.Another approach is locking, as others here suggested, but then note, that cron will not re-run your job just because it completed unsuccessfully because of a lock. So either job2 will have to run in sleep cycles until it doesn't see the lock anymore, or on the contrary sees a flag of job 1 completions, or you'll have to get creative.Why not to trigger 2nd script from the 1st script after it's finished and make it a single cron job?
|
I have two python scripts running ascronjobs.ScriptA processes log files and insert records to atable, ScriptB uses the records to generate a report.I have arranged ScriptA to run one hour before ScriptB, but sometimes ScriptB run before ScriptA finish inserting, thus generating a incorrect report.How do I make sure ScriptB runs right after ScriptA finishes?EDITScriptA and ScriptB do very different things, say, one is for saving user data, the other is for internal use. And somewhere else there maybe some ScriptC depending on ScriptA.So I can't just merge these two jobs.
|
How to make sure a script only runs after another script
|
You need to create a custom module, yes. See themodule developer's guidefor information on exactly how to do this...when you've got a module installed this will work:function mymodule_cron() {
// Do something
}
|
I want to add cron jobs to my Drupal 7 system, but I can't figure out how. The examples I've read on Google doesn't explain at all where to put your code. Do you have to do a module in order to use the my_module_cron()?I have a block which uses some data received from a remote place. A cron job fetching these remote data is what I need to do. Can't I add my cron job in the code for my block?Thanks in advance..
|
Drupal 7 hook_cron - where to put it
|
Normally, you usecrontabto create the file, and it stores it in the correct place for your machine.$ crontab < $HOME/etc/crontabThen you usecrontab -lto list it.$ crontab -l
# @(#)$Id: crontab,v 4.2 2007/09/17 02:41:00 jleffler Exp $
# Crontab file for Home Directory for Jonathan Leffler (JL)
#-----------------------------------------------------------------------------
#Min Hour Day Month Weekday Command
#-----------------------------------------------------------------------------
0 * * * * /usr/bin/ksh /work4/jleffler/bin/Cron/hourly
1 1 * * * /usr/bin/ksh /work4/jleffler/bin/Cron/daily
23 1 * * 1-5 /usr/bin/ksh /work4/jleffler/bin/Cron/weekday
2 3 * * 0 /usr/bin/ksh /work4/jleffler/bin/Cron/weekly
21 3 1 * * /usr/bin/ksh /work4/jleffler/bin/Cron/monthly
$Where I keep my original is immaterial (but it is under source control in$HOME/etcas it happens). The system has its own copy of the file where it needs it.If you try placing the files manually, you will get bitten. It might work, but then again, it might not (and it might change in the future). I wouldn't play the risky game of using other than the kosher command to store crontab files for use bycrontab.
|
A simple question about Crontab, does it matter where I save crontab files? (creating the time-dependent jobs using crontab -e) or can they be read from any directory?I ask because it seemed that my crontab file got deleted because when I used the crontab -l it didn't return anything. However, I think that is because I saved it as a temporary file:Creating more permanent crontab files
|
Saving Crontab files
|
- Open terminal & typesudo crontab -eNow either remove cron command or marked '#' at start of command.
Now save file (ctrl + O, & ctrl +X) & exit.2- Do second optionsudo crontab -rNote: This will remove all cron job.
|
I'm running a webserver with PLESK and installed an extension 'kernel care' which I later on deleted. However, it installed a cronjob which sends me a mail every 4 hours:Cron <root@server> /usr/bin/kcarectl --auto-update
Unknown Kernel (Ubuntu 3.13.0-042stab123.9)I ssh into the server and run crontab -l as rootbut don't see the specific cronjob. However, in /etc/cron.d there is a file kcare-cron and if I cat this file it shows16 */4 * * * root /usr/bin/kcarectl --auto-updateSo thats the one I want to delete. Can I just delete the file kcare-cron?
|
How to remove this cronjob in ubuntu
|
Ahmed,You have use below cron expression to run processor daily at 12:30PM0 30 12 1/1 * ? *Check it here:http://www.cronmaker.com/
|
Below is the syntax I have tried with 0 30 0 * * ? or 0 30 1 * * ?, which should run at 12:30 or 1:30 midnight respectively.Also I have tired running the flow with cron in nifi for every 20 minutes duration, it worked perfectly.But we want it to be run, daily once at particular time as mentioned above example (0 30 0 * * ? or 0 30 1 * * ?).But it is not working. can anyone please guide.Thanks.
|
Nifi processor cron based scheduling
|
This works around the timezone issue, server is at UTC and users in another time zone (with daylight saving time). define a local action and use in cronjob.schedule.rbrequire "tzinfo"
def local(time)
TZInfo::Timezone.get('America/Denver').local_to_utc(Time.parse(time))
end
every :sunday, at: local("11:58 pm") do
#your email sending task
endhope it will help you.
|
We have a Rails 4 application .
What is the best way to schedulewhenevertask in rails in midnight usa with daylight saving ?We need to send email at 11.58pm in night of a day's report .We are usingtzinfogemTZInfo::Timezone.get('America/Denver').local_to_utc(Time.parse('11:58pm')).strftime('%H:%M%p')is not sending email at the time .
|
What is the best way to schedule `whenever` task in rails in midnight usa?
|
-59/5 8 * * * /path/to/whatever.sh >> /var/log/whatever.log 2>&1
*/5 9-20 * * * /path/to/whatever.sh >> /var/log/whatever.log 2>&1
0-30/5 21 * * * /path/to/whatever.sh >> /var/log/whatever.log 2>&1should also work, and easier to read.
|
I am trying to run a cron job every 5 minutes from 8:30 AM to 9:30 PM. I've been searching around the web and here is what I came up with:30,35,40,45,50,55 8 * * * /path/to/whatever.sh >> /var/log/whatever.log 2>&1
*/5 9-21 * * * /path/to/whatever.sh >> /var/log/whatever.log 2>&1
5,10,15,20,25,30 22 * * * /path/to/whatever.sh >> /var/log/whatever.log 2>&1I have looked at cron job generators but they do not seem to address the requirement to start/end on the half-hour. Does anyone have a better or more concise solution?
|
How to create a cronjob that runs every 5 minutes from 8:30 AM to 9:30 PM?
|
You need to use full paths in your scripts. Otherwise,cronwon't know where is that file.so instead of$my_file = 'file.txt';use$my_file = '/path/to/file.txt';Probably you were gettingfile.txtstored somewhere in/.Notecrontabruns in a limited environment, so it cannot assume anything regarding to paths. That's why you also have to provide the full path ofphp, etc.FromTroubleshooting common issues with cron jobs:Using relative paths. If your cron job is executing a script of some
kind, you must be sure to use only absolute paths inside that script.
For example, if your script is located at /path/to/script.phpand
you're trying to open a file called file.php in the same directory,
you cannot use a relative path such as fopen(file.php). The file must
be called from its absolute path, like this: fopen(/path/to/file.php).
This is because cron jobs do not necessarily run from the directory in
which the script is located, so all paths must be called specifically.
|
This question already has answers here:cronjob does not execute a script that works fine standalone(3 answers)Closed7 years ago.root@xx:/var/www/test# which php
/usr/bin/phproot@xx:/var/www/test# ls -la
total 16
drwxrwxrwx 2 root root 4096 Nov 14 09:37 .
drwxrwxrwx 6 root root 4096 Nov 13 15:51 ..
-rwxrwxrwx 1 root root 153 Nov 14 09:35 test.phpThis is mytest.phpfile:<?php
$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file); //implicitly creates fileAnd this is the output ofcrontab -l:#this is ok
* * * * * touch /tmp/hello
#this only creates an empty php_result.log
* * * * * /usr/bin/php /var/www/test/test.php > /tmp/php_result.logroot@xx:/var/www/test# php -v
PHP 5.4.34-0+deb7u1 (cli) (built: Oct 20 2014 08:50:30)The cron job will not run, and the problem is with php. If i run the file manually, all works well.php test.phpRelated question:Why is crontab not executing my PHP script?.
|
php cron job not running [duplicate]
|
Since you are doing aechowithin the cron job script, you need to capture its output somewhere.Yourshebangand file mode (usingchmod +x) are all right, so those aren't the issue here and running without/bin/shshould work fine.Try using the following to see the output incron.logfile (This runs every minute)* * * * * /home/user/simple.sh >> /home/user/cron.logNote that cron jobs run in separate subprocess shell, with reduced environment, so its output won't be visible on your terminal.Regarding sending of email - you need to have some mail package (likepostman,muttetc) configured for the cron daemon to send out error mails.
|
Following is the entry in the crontab:[email protected]45 14 * * * /home/user/simple.shI've also donechmod +xon thesimple.shBut the crontab does not run, it doesn't even send an email.pgrep cronshows an Id. I also tried bouncing crond. But no luck!
Could someone please point out the mistake hereThe simple.sh script is:#! /bin/bash
echo helloThanks
|
Cron job does not run
|
You can check for current usercrontab -lFor list of commands availablecrontab usageFor all user take a look at:/var/cron/tabs
#OR
/var/spool/cron/crontabs
|
Is it possible to check the list of cron jobs that has assigned to my server using putty or winscp or some other ways to check .Because I could find cron job tab in side my cpanel
|
How to check whether my server has assigned any cron job or not
|
+25Definitely possible! You can monitor external cron jobs as described here:https://wiki.jenkins-ci.org/display/JENKINS/Monitoring+external+jobsYou can also add cron job (-like behavior) to Jenkins by creating a freestyle software project and add "Execute shell" as build process.
It's a bit more convenient since you can also trigger the execution via Jenkins ("Build now").
|
We are using a dedicated Amazon Ubuntu ec2 instance as Cron server, which executed 16 cron jobs at different time intervals i.e, 10 cron jobs in morning 4:15 - 7:15 and the rest @ 23:00 - 23:50. I get the results via email. I want to configure something, which shoots email message at the end of they day listing the cron jobs that are executed successfully and the one that failed.I have a jenkins configured ubuntu instance for auto-building Dev, Beta, Staging & Live environments. Can i add thesecron jobs(shell scripts) as external jobs in thejenkinsand monitor them. Is it possible?
|
Jenkins to monitor external cron jobs
|
Seems like you're running into cron job issues. I would instead turn your script into a daemon, that way it can run perpetually without fear of overlaps or finishing too fast.Here's a tutorial how to do it.http://kevin.vanzonneveld.net/techblog/article/create_daemons_in_php/
|
I have a php script that can take anything from 2 to 10 minutes to execute. It fetches info from around the web so its time depends on how fast lots of other things are talking.I used to run the script on a cron every 15 minutes, but sometimes it only takes 2 minutes to run.So I wondered if I can somehow make it run perpetually - setting itself going again as soon as it finishes its task? That way, however long it takes, it will always start agaiun straight away.
|
php script that calls itself when it is finished - indefinately
|
ok well here's a solution:<key>StartCalendarInterval</key>
<array>
<dict>
<key>Minute</key>
<integer>0</integer>
</dict>
<dict>
<key>Minute</key>
<integer>55</integer>
</dict>
</array>So it seems you need to set up a dict for each repeated job.
|
I'm using mac osx 10.6 - and it seems that the minutes parameter determines how many minutes past the hour that the job runs. But how do you set up a job to run ever x minutes past the hour.I've tried setting up minutes as an array of several numbers and an array with one string which is "*/5" i.e. similar to every five minutes syntax for crontab.
|
Run a job every x minutes with startCalendarInterval in launchd (like using step values "*/x" in cron)?
|
* * * * * /bin/sh /home/myuser/shellscript.shor* * * * * /bin/bash /home/myuser/shellscript.shworked for me in Macosx 10.6 as rootuser
|
I'm trying to execute a shell script from cron on Freebsd.To test whethercrontabis working at all, I wrote the line* * * * * echo "Hello" > /home/myuser/logileand it work fine.But when trying to execute any script it doesn't do anything, not even an error. (In the script I tried to run is just the same echo command)
Below is the output ofcrontab -l:SHELL=/bin/sh
PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
HOME=/home/myuser
MAILTO=myuser
* * * * * /home/myuser/shellscript.sh > /home/myuser/logfileWhy is the script not getting executed, althoughcrontabis obviously running?
Permission for all files are set torwxr-xr-x.
|
Crontab no error but doesn't execute script
|
Maybe I'm misunderstanding you, but the cron config files will let you do this (without Python).
You can add something like this to you cron.yaml file:cron:
- description: job that runs every minute
url: /cronjobs/job1
schedule: every minuteSeeGoogle's documentationfor more info on scheduling.
|
I look for a possibility to create pseudo-cronjobs as I cannot use the real jobs on UNIX.Since Python scripts can run for an unlimited period, I thought Python would be a great solution.On Google App Engine you can set up Python scripts and it's free. So I should use the App Engine.The App Engine allows 160,000 external URL accesses (right?) so you should have 160000/31/24/60 = 3,6 accesses per minute.So my script would be:import time
import urllib
while time.clock() < 86400:
# execute pseudo-cronjob file and then wait 60 seconds
content = urllib.urlopen('http://www.example.org/cronjob_file.php').read()
time.sleep(60)Unfortunately, I have no possibility to test the script, so my questions are:
1) Do you think this would work?
2) Is it allowed (Google TOS) to use the service for such an activity?
3) Is my calculation for the URL accesses per minute right?Thanks in advance!
|
Google App Engine for pseudo-cronjobs?
|
you can easily do that with when() method$schedule->command('command')->when(function (){
return Carbon::create(2020,4,28,13)->isPast();
});
|
I want to run a cron just once at a custom date & time entered by the user in a form. What is the best way to do this?I found that a custom cron can be scheduled in laravel like this->cron(‘* * * * * *’);Run the task on a custom Cron schedule.But I could not find the time format what the * mean.Or much simpler, can it be done like this by adding the date and time.->at('28/04/2020 13:00');How can this be done?
|
One time custom cron schedule in laravel
|
Fixed the issue thanks to another source. I was not using the sendmail's full path. I was just stating "| sendmail -v email" and not sendmails full path which was "/usr/sbin/sendmail" for me. Not sure if links are allowed here but below is where I found the answer.https://www.unix.com/red-hat/271632-bash-sendmail-command-not-found.html
|
I'm trying to run a sendmail command in a Red-hat Linux environment on a bash shell script through a cronjob. I can run this script successfully when it is ran manually and every other job within the shell runs correctly other than the mailing part.I have never used sendmail and am not sure if I need to restructure how it is being presented.I have tried mail and mailx. I am able to send the emails but the log file contain many weird characters that it put the text format into a att00001.bin attachment on the email which I do not want. The sendmail command seems to be the only one that doesn't send an attachment when ran manually. Other cron jobs works correctly and are able to send emails they just do not have the special characters in the log file.echo '##################################################'
date
echo '##################################################'
#Run Script and write to log file
/comp/gfb281m.sh > /usr/local/bin/oracle/getload/getload.log 2>&1
#Send log file to developer group
(echo "Subject:GetLoad Shell"; echo; cat
/usr/local/bin/oracle/getload/getload.log) | sendmail -v[email protected][email protected]When ran this cron job should send the contents of the getload.log file to a group a of users.
|
Linux sendmail command not sending mail while in a cron
|
cronlogs each command it runs to syslog, and on your system the syslog ends up in the journal as well. As far as I’m aware,crondoesn’t have an option to disable that, but you can hide those messages by selecting only those journal messages received via stdout:journalctl -u cron _TRANSPORT=stdout(-u cronmight be-u crondor something like that on CentOS, I’m not sure.)
|
Disclaimer: the following describes things done for learning purposes in CentOS 7.I want to redirect the output of a crontab job tojournalctl.
When I have the following record, it just sends a mail to root user.# crontab -l
* * * * * echo "Hello World"I've read aboutsystemd-catwhich can execute a process, piping it's output to the journal.
So I made it like this:# crontab -l
* * * * * systemd-cat -t "cron-bot" echo "Hello World"But now I receive two log messages every minute:{
"_TRANSPORT" : "syslog",
"SYSLOG_IDENTIFIER" : "CROND",
"MESSAGE" : "(root) CMD (systemd-cat -t \"cron-bot\" echo \"Hello World\")",
"_CMDLINE" : "systemd-cat -t cron-bot echo Hello World",
}
{
"_TRANSPORT" : "stdout",
"SYSLOG_IDENTIFIER" : "cron-bot",
"MESSAGE" : "Hello World",
"_COMM" : "echo",
}or, in short format:Sep 06 08:58:01 hostname CROND[13417]: (root) CMD (systemd-cat -t "cron-bot" echo "Hello World")
Sep 06 08:58:01 hostname cron-bot[13417]: Hello WorldCan someone explain this behavior to me? I'd like to receive only the job ouput (cron-bot[13417]: Hello World)
and do not receive the command itself (CROND[13417]: ...) but mostly I'm asking this to learn more about the topic.
|
Crontab + Journalctl: extra messages
|
First of all, there are a couple of problems in your grep regular expression:The repetition count ({1,3}) applies to its preceding atom (i.e. '.') rather than the next one (i.e. '[0-9]').An unescaped dot ('.') in the regex matches any character, which hides the previous error. Your regex (192.168.0.{1,3}[0-9]) matches192.168.0.123as follows:192.168.0 matches 192.168.0
.{1,3} matches .12
[0-9] matches 3But it would also match the following strings:192116810abc1
192.681.012.9The correct regex must be192\.168\.0\.[0-9]{1,3}and it must be quoted, so that bash passes it to grep literally:grep -Eo '192\.168\.0\.[0-9]{1,3}'Yet, the wrong regex can hardly explain the problem your are seeing with cron.One problem may be that you are using a fixed namenew.txtfor your temporary file. If you do the same in your other scripts, or if you set up this cron job to run every minute while it takesnmapmore than a minute to complete scanning the network, thennew.txtmay be overwritten at the wrong time.Please fix your script as follows and check if the problem disappears:#!/bin/bash
tmpfile="$(mktemp)"
trap "rm $tmpfile" EXIT
nmap -sn 192.168.0.1-255 | grep -Eo '192\.168\.0\.[0-9]{1,3}' > "$tmpfile"
date >> network_log
echo ---------------------------- >> network_log
cat "$tmpfile" >> network_log
|
I have a bash script that does this:nmap -sn 192.168.0.1-255 | grep -Eo 192.168.0.{1,3\}[0-9] > new.txt
date >> network_log
echo ---------------------------- >> network_log
cat new.txt >> network_logScans the network, and appends results to file network_log with a timestamp.
After running it manually, the network_log file looks like this:Tue 13 Sep 2016 11:22:23 EDT
----------------------------
192.168.0.1
192.168.0.2
192.168.0.45whereas the cronjobs produce the following outputs in my network_log file:Tue Sep 13 17:46:00 EDT 2016
----------------------------with no ip results.
Note: the cronjob is running from root user so it has all the elevation it needs to scan the entire network.
|
different results between crontab and running script manually
|
No, it's not atomic. Not even a little bit atomic.The redirection does two things:It opens the fileby name, creating it if necessary.It truncates the file.After that, the utility is started, with itsstdinassigned to the opened file.If two scripts do that more or less at the same time, they will both end up writing the same file, but since they will have independent file descriptors, each process will overwrite the other process's output, resulting in a grand interleaving of bytes, some from one process and some from the other.Another common race condition relates to the fact that the file is truncated (by the shell) before the utility starts executing. Consequently, even if the utility only writes a single line to the file, it is possible that a concurrent utility which reads the file will find that it is empty.
|
I've weird problem with my crontab job. My crontab job does the following:program > fileSometimes however file gets filled with random data that I can't explain.I wonder if it could be the previous crontab job that's taking longer to run and it somehow mixes its results infilewith current crontab job?Overall my question is: is>operation atomic? Meaning if two programs do> file, then the last one to finish will have its data infile?
|
Is bash > redirection atomic?
|
You are probably running your script from cron with a different version of Python that doesn't support the dictionary comprehension syntax.To fix this, either explicitly add your desired Python version in the shebang line:#!/usr/bin/env python2.7or launch your script from cron through the correct command:* * * * /usr/bin/python2.7 /path/to/script.py
|
I have a shell script that includes execution of a python script. When I run it manually in terminal, it works fine. However when I execute the shell script in a cron job, the python script fails.The error is apparently triggered while functions are being imported from module1 into module2. The function referenced by the error is not among the functions being imported, nor does the function where the syntax error is supposed to be elicit an error when it is executed by itself.Here's the error that gets logged when I run the cron job:File "/Users/me/module2.py", line 5, in <module>
from module1 import consolidate_rankings, build_all
File "/Users/me/module1.py", line 159
things = {row["thing"]: row for row in rows}
^
SyntaxError: invalid syntaxThe module2 script is pretty straightforward:#!/usr/bin/env python
from module1 import consolidate_rankings, build_all
consolidate_rankings()
build_all()Here's the line that calls this in the shell script:python /Users/me/module2.pyAnyone have any idea what's going on here?
|
Python script elicits error when run in cron job but at no other time
|
You want to add the following options to the 'screen' commands (e.g. before-S):-d -mFrom the manpage:-d -m Start screen in "detached" mode. This creates a new session but
doesn't attach to it. This is useful for system startup
scripts.
|
I've tried adding this to my crontab:@reboot /root/startupThe "startup" file:#!/bin/sh
svnserve -d -r /root/svnrepos/mainres
svnserve -d -r /root/svnrepos/mapres --listen-port=3691
screen -S mta ./mtaserver/mta-server > log1
screen -S mapmta ./mapserver/mta-server > log2
exit 0Now svnserve commands run fine. The problem is with the screen command.log1 and log2 files have the same content which is: Must be connected to a terminal.What I'm trying to do is start the 2 executables on startup, and then later have a way to access them.Is there a way to do this?
|
Run "screen -S name ./script" command on @reboot using crontab
|
The easiest way I can think of is to log the output to disk and have a console window constantly checking to see if the logfile has been altered and printing the changes.crontab:*/1 * * * * /root/myscript.sh | tee -a /path/to/logfile.login console:tail -F /path/to/logfile.logThe problem with this is that you will get an ever growing log file which will need to be periodically deleted.To avoid this you would have to do something more complicated whereby you identify the console pid that you wish to write to and store this in a predefined place.console script:#!/usr/bin/env bash
# register.sh script
# prints parent pid to special file
echo $PPID > /path/to/predfined_location.txtwrapper script for crontab#!/usr/bin/env bash
cmd=$1
remote_pid_location=$2
# Read the contents of the file into $remote_pid.
# Hopefully the contents will be the pid of the process that wants the output
# of the command to be run.
read remote_pid < $remote_pid_location
# if the process still exists and has an open stdin file descriptor
if stat /proc/$remote_pid/fd/0 &>/dev/null
then
# then run the command echoing it's output to stdout and to the
# stdin of the remote process
$cmd | tee /proc/$remote_pid/fd/0
else
# otherwise just run the command as normal
$cmd
ficrontab usage:*/1 * * * * /root/wrapper_script.sh /root/myscript.sh /path/to/predefined_location.txtNow all you have to do is runregister.shin the console you want the program to print to.
|
I have written a shell script (myscript.sh):#!/bin/sh
ls
pwdI want to schedule this job for every minute and it should display on the console. In order to do that I have donecrontab -e:*/1 * * * * /root/myscript.shHere, it's display the output in the file/var/mail/rootrather than printing on the console.What changes I have to make inorder to print the output on console?
|
Cron jobs output on console
|
You should probably use an absolute path to your casper script, something like:30 9 * * * /usr/local/bin/casperjs /absolute/path/to/lib/fsaupload.js arg1 arg2 arg3My two cents.Edit:Okay, it was a bit silly. You can also set a custom path to thephantomjsexecutable by setting thePHANTOMJS_EXECUTABLEenvironment variable:$ export PHANTOMJS_EXECUTABLE="/path/to/phantomjs"Then run your script as usual:/usr/local/bin/casperjs /absolute/path/to/lib/fsaupload.js arg1 arg2 arg3Hint: If your crontab runs as another user, check that it has access to the phantomjs path.Hope it helps (and works).Edit againWait, the stack trace you get says you're using an old version of CasperJS (eg. thesubprocessmodule is no more used). Try with a more recent version :)
|
I'm trying to run a casper.js script via cron. Everything works fine when I run the script manually, but when I run it via cron I get the following errors:Traceback (most recent call last):
File "/usr/local/bin/casperjs", line 46, in <module>
status = subprocess.call(CASPER_COMMAND)
File "/usr/lib/python2.6/subprocess.py", line 480, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.6/subprocess.py", line 633, in __init__
errread, errwrite)
File "/usr/lib/python2.6/subprocess.py", line 1139, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directoryMy crontab entry is:30 9 * * * /usr/local/bin/casperjs lib/fsaupload.js arg1 arg2 arg3I've also tried30 9 * * * python /usr/local/bin/casperjs lib/fsaupload.js arg1 arg2 arg3Which gives me the same result. Any ideas? I'm guessing it might be apathissue, but no idea where to go from here!
|
Running a casper.js script from cron
|
Useenvin the shebang line to look things up in the path:#!/usr/bin/env ./script/runner
|
I'm writing a rails app and need to run come scripts through./script/runnerwhile i could put#!/home/cannon/src/timetracker/script/runnerat the top, that wont work in production where it needs to be more like#!/var/www/loclahost/htdocs/timetracker/script/runner -e=productionsince./scriptis not in my path, and I don't want it to be, how can I allow this to be set up,I am using a cron job to run it on a Linux box
|
have a relative shebang line
|
You could do this, and give up the exactly on the hour, but it will be close...(Example came from a app I was debuging)cron:
- description: Description of what you want done...
url: /script/path/goes/here
schedule: every 60 minutes synchronized
timezone: America/New_YorkBelow is a screenshot of the logs, the app gets no traffic right now,
99% of those entries are all the cron entry.---edit---Just re-read the docs as well and maybe this might be better,schedule: every 60 minutes from 00:00 to 23:59
|
I need to run a task every hour on the hour (00:00, 01:00, 02:00, ..., 23:00) every day of the week, but can't seem to find an example in App Engine's docs of how to do this.There is an example of running at ask every hour, but this doesn't fit because the "start" of that hour depends on when you deploy the application. That is, if I deploy at 4:37 PM, the cron scripts will get executed at 5:37, 6:37, ... instead of 5:00, 6:00, ...So far the only way that looks like it would work is to have 24 different cron entries, one for the specific hour of each day set to run each day at that specific time.Does anyone know of anything that would let me use a schedule like "every hour at :00" or even "every day 00:00, 01:00, ... 23:00"?
|
Run a task every hour on the hour with App Engine's cron API
|
You need to let goaccess know you are piping data using the-. e.g.,* * * * * sudo zcat -f /var/log/nginx/access.log* | goaccess - -o /home/me/some/path/bigger_report.html
|
In my root crontab (sudo crontab -e) I have this job to generate Go Access log reports:* * * * * goaccess /var/log/nginx/access.log -o /home/me/some/path/report.htmlIt works just fine. I also have this job to generate a report that spans multiple days:* * * * * sudo zcat -f /var/log/nginx/access.log* | goaccess -o /home/me/some/path/bigger_report.htmlCron says it runs but it doesn't actually seem to run. I've looked around and tried a bunch of things (including following the list here -https://stackoverflow.com/a/22744360/3761310) but still can't get this job to run. If I run the command myself it generates the file as expected. I also tried just the part before the pipe, outputting into a txt file and that worked. So I suspect it's some interaction with Go Access.When I enabled cron logging, this is what it says when that job runs:(root) CMD (sudo zcat -f /var/log/nginx/access.log* | goaccess -o /home/me/some/path/bigger_report.html)Any pointers? Thanks!
|
Cron job for generate Go Access report not working
|
The issue I encountered in such scenario is that when you run container using unprivileged user you cannot start cron due to lack of access to cron.pid file.Therefore the best workaround is to setSUIDfor the cron binary which will allow to run it with root privileges using your www-data user. You should also make sure to add cron settings to the correct user's crontab.You can modify your Dockerfile in a following way:WORKDIR /app
ADD ./entrypoint.sh /entrypoint.sh
RUN chmod 777 /entrypoint.sh
ADD ./crontab.txt /etc/cron.d/hello-cron
RUN crontab -u www-data /etc/cron.d/hello-cron # <---- setting crontab for user www-data
RUN chmod u+s /usr/sbin/cron # <---- setting setuid
RUN touch /var/log/cron.log
RUN usermod -s /bin/bash www-data
USER www-data
ENTRYPOINT /entrypoint.shThis should work just fine.
|
I've got a php container which hosts a Symfony web application. I need to use background scripts and initiate them from crontab. And it seems to work as long as I use root user. However, when I switch user to "www-data" - it stops working.
My idea was to run php-fpm as user www-data and also log into "www-data" when I enter to the container. But crontab can be defined for root user, since it allows to prefix commands with username.my entry point file contains:#!/bin/bash
npm install
cron &
php-fpmand my docker file looks like this:WORKDIR /app
ADD ./entrypoint.sh /entrypoint.sh
RUN chmod 777 /entrypoint.sh
ADD ./crontab.txt /etc/cron.d/hello-cron
RUN chmod 0666 /etc/cron.d/hello-cron
RUN crontab /etc/cron.d/hello-cron
RUN touch /var/log/cron.log
RUN usermod -s /bin/bash www-data
USER www-data
ENTRYPOINT /entrypoint.shThe above works if I skip lineUSER www-dataBut I would like to first initiate cron (for root) and later switch default container user to www-data... so I've tried also:ENTRYPOINT /entrypoint.sh
USER www-dataBut it doesn't work as well.
Any help will be appreciated :)
|
Running cron in a container
|
The first crontab entry looks correct. Since there is no#! /bin/bashline, you might need to put bash in front of the invocation, e.g.*/2 * * * * /bin/bash /root/todo-api/workspace/docker.sh c4e842c79337According todocker inspectUsagedocker inspect [OPTIONS] NAME|ID [NAME|ID...]the second invocation without$CONTAINERmust fail, becauseinspectexpects a name or some id.To debug this further, follow this questionHow to debug a bash script?and keep the output from stderr, e.g. remove2>/dev/null.
|
I want to execute a script with some parameters as a cron job. I have configured the crontab usingcrontab -ewith the following content*/2 * * * * /root/todo-api/workspace/docker.sh c4e842c79337but it is not working. When I used*/2 * * * * /root/todo-api/workspace/docker.shit worked. How to pass parameters while invoking a script in cron? Here is my docker.sh script and it works if I directly execute it from shell.CONTAINER=$1
RUNNING=$(docker inspect --format="{{.State.Running}}" $CONTAINER 2> /dev/null)
if [ $? -eq 1 ]; then
echo "UNKNOWN - $CONTAINER does not exist."
exit 3
fi
if [ "$RUNNING" == "false" ]; then
echo "CRITICAL - $CONTAINER is not running."
curl -H "Content-type: application/json" -X POST -d '{"routing_key": "3ef61cda125048a390d46cdb8d425590","event_action": "trigger","payload": {"summary": "Docker Container '$CONTAINER' down", "source": "'$CONTAINER'", "severity": "critical" }}' "https://events.pagerduty.com/v2/enqueue"
exit 2
fi
echo "OK"
|
How to pass parameters while invoking script in cron?
|
st expression: 8:00 AM, 5:00 PM 2nd expression: 12:30 PM
|
I would like to trigger a build based on two different sets of cron expressions.Example:1st expression: 8:00 AM, 5:00 PM2nd expression: 12:30 PMLet me know any suggestions.
|
Multiple cron expressions to trigger jenkins build
|
Use&&if you only want to execute the second command if the first command succeeds.sudo sync && sudo sysctl -w vm.drop_caches=3Use;if you would like to execute the second command regardless of the result of the first command.sudo sync; sudo sysctl -w vm.drop_caches=3Thiscronwill run the commands every hour:0 * * * * sudo sync && sudo sysctl -w vm.drop_caches=3However your should setup theroot'scrontabinstead of running the commands withsudo.sudois not necessary to run your commands in this context, since it'll be invoked asrootanyway. This opens uproot'scrontab.sudo crontab -eThecronwithoutsudowill look like this.0 * * * * sync && sysctl -w vm.drop_caches=3
|
I don't have enough memory ram in my digitalocean droplet ( I know, I should optimize the running modules and the code instead, and I'll Do that, but I need to buy some time until I Can Do it.. )I'd like to create a cron every few hours that runs this:sudo sync
sudo sysctl -w vm.drop_caches=3But I would like to make sure that the first is finished before run the second,How could I do that?
|
Run a cron with 2 commands, and wait for first to finish to run second
|
Call your script in the CRON tab with your function name as an argument:* * * * * /path/to/php /var/www/webpage/yourphp.php pwdTimeoutAnd retrieve the value of your argument with$argv:$functionName = $argv[1]; // outputs pwdTimeout ([0] is the filename)Please note that you can also use a key for your argument ($ php yourphp.php function=pwdTimeout) but you would need toexplode()it, like so:$parameters = explode('=', $argv[1]); // outputs array('function' => 'pwdTimeout')Finally, you can usegetopt()with the following call:* * * * * /path/to/php /var/www/webpage/yourphp.php -f pwdTimeoutAnd use it like so:$parameters = getopt('f:'); // outputs array('f' => 'pwdTimeout')
|
I want to execute a php function in crontab like it is possible in a URL:yourdomain.com/yourphp.php?function=pwdTimeoutI have tried something like this but it doesn't work* * * * * /var/..../webpage/yourphp.php?function=pwdTimeoutHow can I execute a php function with the help of crontab. Help is highly appreciated.My php-File looks like:<?php
define ('database', $database); // the variables are defined and tested
define ('host', $host);
define ('db_username', $db_username);
define ('db_password', $db_password);
if(isset($_GET['function'])){
$view = new functions();
$view->$_GET['function]();
}else{
echo 'Function not found'
}
class functions{
function getUsername(){....}
function setPassword(){...}
function pwdTimeout(){...}
}
?>where should I make changes in my code? thanks:)
|
Execution of a php function in crontab
|
cron probably just sets itself to your home directory. If you need your script to run in a particular directory consider using something likeimport os
os.chdir(os.path.dirname(os.path.abspath(__file__)))at the top of your script although really your script should not care where it's run from. All your file paths in the script should be relative to the script, using something like:scriptdir = os.path.dirname(os.path.abspath(__file__))
mypath = os.path.join(scriptdir, 'data', 'mfile.dat')
... etc ...
|
I have a script in python under Linux that needs to determine the current working directory. The part of program that does this is:import os
cwd = os.getcwd()
print cwdWhen I run the program it gives me the right answer:/home/johny/LST/CTBut when I run it using crontab, it gives me this:/home/johnyEven when I put it in deeper folders, the same path results. Does anybody know what can be the problem?
|
Wrong path results the python program runs using crontab
|
You could work around it by writing at the top of the script (Bashism):USER=$(whoami)or old-style:USER=`whoami`... assuming you havewhoamiin thePATH, which can also be set in thecrontabjust like several (most?) other variables. I.e. you can also set the variable incrontabitself (at least in Vixiescron) - seeherefor example.
|
I have a script that requires the env variable USER to be set. As the script is used by several users, I can't just doexport USER=xxxat the beginning of the script. I could define in thecrontab, but I was just wondering whether there is a good way of pulling it in.I tried sourcing.bashrcand.profile, but neither define USER, plus on Ubuntu.bashrcsimply returns on non-interactive shells.
|
Export USER env variable for use in cron
|
I was able to accomplish the cron job by using a program calledwget. I setup task scheduler to run the wget.exe at my specified time with these arguments:wget -q -O - http://theurl.com > tmp.txtThis would load the website and store it to a temporary text file which is overwritten next time it is used.
|
I wanted to use my local server which is running Windows 7 to take advantage of the task scheduler to setup some cron jobs for some of my php files.I can do this currently by:start http://theurlWhich opens in my default browser. However I was hoping to accomplish this without physically opening a browser so when I come back to my computer after a few days I don't have millions of Chrome windows open.How can I load a URL in Task scheduler without opening a browser client viacmd?
|
Open URL via cmd without opening a browser
|
Cron syntax issec min hour day day_of_month month day_of_week yearSo what you would want is0 0,35 * * * * ?So it will fire on minutes 0 and 35 of each hour.See theQuartz docsfor this, as Spring is using Quartz as scheduler here. Those docs also explain the special chars like * ? - , and others.
|
Java spring - I have following cron expression for cron job.0 0/35 * * * ?But above mentioned cron expression fires once in an hour and like as follows1:35
2:35
3:35
4:35I want to fire every after 35 mins instead once in an hourany quick suggestion ?
|
Spring cron expression every after 30 minutes
|
The clue is in the error message:/bin/sh: cannot create : nonexistentNotice that it says "sh". The Bourne shell doesn't support some features that are specific to Bash. If you're using Bash features, then you need to tell Bash to run the script.Make the first line of your file:#!/bin/bashor in your crontab entry do this:* * * * * /bin/bash scriptnameWithout seeing your crontab entry and your script it's hard to be any more specific.
|
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed5 years ago.Improve this questionI've written a backup script for our local dev server (running Ubuntu server edition 9.10), just a simple script to tar & gzip the local root and stick it in a backup folder.
It works fine when I run :$ bash backups.shbut it wont work when I run it through crontab.59 23 * * * bash /home/vnc/backups/backup.sh >> /home/vnc/backups/backup.log 2> $1I get the error message/bin/sh: cannot create : nonexistentThe script makes the tar.gz in the folder it is running from (/home/user1), but then tries to copy it to a mounted share (/home/backups, which is really 192.168.0.6/backups) from a network drive, via using fstab.
The mounted share has permissions 777 but the owner and group are different to those running the script.
I'm using bash to run the script instead of sh to get around another issue I've had in the past with "bad substitution" errorsThe first 2 lines of the file are! /bin/bash
cd /home/vnc/backupsI'm probably not supplying enough information to fully answer this post yet but I can post more information as necessary, but I don't really know where to look next.
|
Shell script and CRON problems [closed]
|
I would:extract the user's crontab withcrontab -l > somefilemodify that file with the desired jobimport the new crontab withcrontab somefile
|
I need to upload a file (bash script) to a remote sever. I use the scp command. After the file has been copied to the remote server I want to create a cron entry in the crontab file on the remote server.
However, the file upload and writing the cron entry need to occur within a bash shell script so that I only need to execute the script on my local machine and the script is copied to the remote host and the cron entry is written to the crontab.Is there a way that I can use an ssh command, within the script, that logs me into the remote server, opens the crontab file and writes the cron entry.Any help is very welcome
|
Creating cron entry on server using ssh login within shell script
|
$filename = dirname(__FILE__) . "/online_users.txt";
|
I run a windows 2003 server and tried to run a code like this every 15 minutes:require("db_connect.php");
$conn = db_connect();
//list online brukere - flytt funksjon til separat side for bedre ytelse
$time = time() - 900;
$query ="SELECT username FROM tbl_user WHERE last_online >= $time";
$online_users;
if ($result = $conn->query($query)) {
while ($row = $result->fetch_assoc()) {
$online_users .= $row["username"].":";
}
$result->close();
}
$filename = "online_users.txt";
$fp = fopen($filename,"w");
fputs($fp,$online_users);
fclose($fp);When I go to the url or run it from the command line it works and write to file. But the task just run and don't save the file.. What's wrong?
|
cron job won't write to file
|
All about Cron on one pageAn excellent, and very thorough tutorial. Covers all aspects of cron, from background to practical examples. If it's not on this page, it's not worth knowing.also covers similar/related toolsanacron,atandbatch, as well as the general concepts of time in Unix.
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the help centerfor guidance.Closed11 years ago.Kindly tell me where to find excellent tutorials on cron. I have searched google for this. But most sites give tutorials which are not complete. I dont need links to those tutorials which are incomplete and shabby.
|
Tutorials on cron [closed]
|
-1Just dopython FILE | at TIME > app.logreplace:
FILE - Your .py file (include the shebang)TIME - Your time
|
When I try to use cron to execute my python script in a future time, I found there is a command at, AFAIK, the cron is for periodically execute, but what my scenario is only execute for once in specified time.
and my question is how to add python script to at command,
also it there some python package for control the at commandMy dev os is ubuntu 10.04 lucid,and my product server is ubuntu-server 10.04 lucid version.
in fact, I want through python script add python script tasks to at command, which file's change can effect at command add or remove new jobs
|
How to use at command to set python script execute at specified time
|
Windows has theScheduled Taskscontrol panel applet (or management console plug-in on later versions of Windows) but you can also access it viaschtasks.exeif you want to automate it from the command line.In addition, you can also useatfrom the command line to schedule a task.
|
I want to know if there is an equivalentcronin Windows and how I can use it programmatically using PHP.
|
Is there an equivalent to cron in Windows?
|
The issue was that some Alpine Docker containers come without thebusybox-initscripts packageinstalled. After installing this, crond is running as a service. One other hiccup I ran into is thatrun-parts, the command the executes the files in the/etc/periodicfolders expects there to be no extension, so I stripped that, and everything is working now.The working Dockerfile looks like this:FROM node:12.13.0-alpine
RUN apk upgrade --available
RUN apk add --no-cache tini openrc busybox-initscripts
WORKDIR /opt/app
COPY runScraper /etc/periodic/15min/
RUN chmod a+x /etc/periodic/15min/runScraper
COPY . .
RUN chmod a+x startup
ENTRYPOINT ["/sbin/tini", "--"]
CMD ["./startup"]
|
I'm trying to run an Node 12.13.0 Alpine Docker container that runs a script every 15 minutes. According toAlpine's wiki cron section, I should be able to just add a RUN task in the Dockerfile to run crond as a service via:rc-service crond start && rc-update add crondThis however returns an error:rc-service: service `crond' does not existRunning a separate Docker container just to run the cron task against this Docker container isNOTan option. This container is already extremely lightweight, and doesn't do much.Here is my Dockerfile:FROM node:12.13.0-alpine
RUN apk add --no-cache tini openrc
WORKDIR /opt/app
COPY script.sh /etc/periodic/15min/
RUN chmod a+x /etc/periodic/15min/script.sh
RUN rc-service crond start && rc-update add crond
COPY . .
RUN chmod a+x startup.sh
ENTRYPOINT ["/sbin/tini", "--"]
CMD ["./startup.sh"]Any help here would be appreciated.
|
Alpine: "service `crond' does not exist"
|
Spring Scheduler does not support the "L" input string. So, you need to do a workaround.First, call scheduler for each of the possible last days of months (28,29,30,31).Then, inside the function block check with an if block whether this is the last date. If it is, then perform the expected task.Code will be like this -@Scheduled(cron = "0 15 10 28-31 * ?")
public void monthEndSchedule() {
final Calendar c = Calendar.getInstance();
if (c.get(Calendar.DATE) == c.getActualMaximum(Calendar.DATE)) {
// do your stuff
}
}
|
I wanted to run a spring scheduler job at 'last day of every month at 10:15' and 'First Sunday of every month' -I have tried below - but it is giving error while initializing spring context:org.springframework.boot.SpringApplication:Application startup failed
java.lang.IllegalStateException: Encountered invalid @Scheduled method 'monthEndSchedule': For input string: "L"@Override
@Scheduled(cron = "0 15 10 L * ?")
public void monthEndSchedule() {
//
}Though below works which runs at 'every day 1 am'@Override
@Scheduled(cron = "0 0 1 * * ?")
public void surveyDailySchedule() {
//
}Cron expression reference I have used :http://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/crontrigger.html
|
Spring schedule - last day of month not working
|
I went with this:H H(0-7) * * *which seems to be giving it a random time between 12 and 7 which is good for me. You could also do something like:def rand = Math.abs(new Random().nextInt() % 24) + 1;
triggers {
githubPush()
cron('H ' + rand + ' * * *')
}but seems extra as what I did worked.
|
Hi so right now I have a basic cron that runs my stuff twice a day at 1 and 6. Something like:H 1,18 * * *The problem is I have like 100 things kicking off at this time which is clogging up my machine. I want to randomly generate a time once a day for each job to run. It's ok if 5-7 are going at once. So I guess my question is. For one is this possible? If so is there a best practice for this? I'm loading everything up in groovy so I was just thinking about generating a number between 1-24 and adding it to this:cron('H 1,18 * * *')if that's possible. But I feel like that would still clog me up since I have so many things kicking off.
|
How to set up cron to run once a day at random times
|
cron jobs run with a very basic environment setup; among other things, the default PATH is just/usr/bin:/bin. It doesnotuse the user's regular shell setup. There are several ways to solve this:Use the full path in the script (i.e./sbin/reboot).Set PATH in the script before usingreboot(i.e.PATH=/usr/bin:/bin:/usr/sbin:/sbin).Set PATH in the crontab before the entry for your script (syntax is the same as in the script).
|
I've set a script in my root crontab that is supposed to restart my machine with therebootcommand.However, I am getting areboot: command not founddespite the fact thatrebootis in the root user's path.$ sudo su
$ which reboot
/sbin/reboot
$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/go/binMy script:#!/bin/bash
ping 8.8.8.8 -c 1 > /dev/null 2>&1; exit_code=$?
time_stamp=$(date +"%Y%m%d-%H%M")
if [ $exit_code -ne 0 ]; then
(1>&2 echo "$time_stamp: failed with exit code $exit_code; restarting now")
reboot
else
echo "$time_stamp: ok"
firoot user crontab:$ sudo crontab -l
58 * * * * /home/pi/github/ping-restart/ping-restart.sh >> /home/pi/github/ping-restart/cron.log 2>&1
$ sudo su
58 * * * * /home/pi/github/ping-restart/ping-restart.sh >> /home/pi/github/ping-restart/cron.log 2>&1...yes, this is only a temporary workaround while I figure out why the internet keeps dropping.
|
Running script in crontab--reboot: command not found
|
When a scheduled webjob is started, Azure places a lock file. This lock file will remain until the scheduled webjob is completed. If there's an attempt to fire up another scheduled job, you'll get a ConflictException.You can read about the lock filehere. And the code that checks to see if another job is already running ishere.
|
I have a Azure web job that is scheduled to run every 5 minutes using the cron expression in the settings.job file. If the process doesn't finish within 5 minutes will Azure kick off another instance of the job or will it wait until the first one finishes?I would like to make sure it waits until the first one finishes so it isn't running multiple instances.
|
Does Azure start up another instance of a scheduled web job if it is already running?
|
Put your desired minute in the minute column, and then use*/2in the hour column to get it to run every two hours.24 */2 * * * <your command>
|
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.Closed7 years ago.Improve this questionI want to run cron job every 2 hours In the X minuteExample:every 2 hours In the 24 minute00:2402:2404:24etc.
|
Run cron job every 2 hours In the X minute [closed]
|
Your script is written for bash; these errors are almost certainly indicative of it being run with/bin/shinstead.Either add an appropriate shebang and ensure that it's being called in a way that honors it (/path/to/scriptrather thansh /path/to/script), or fix it to be compatible. For instance:case $action in
*start*)
echo "start recording"
./gone.sh
exit 1
;;
*stop*)
echo "stop recording"
./gone.sh
exit 1
;;
esac
|
I have the following code: (record.sh)cd $(dirname $0)
dt=$(date '+%d/%m/%Y %H:%M:%S');
echo $dt;
read action < /home/nfs/sauger/web/pi/action.txt
echo $action;
if [[ $action == *"start"* ]]
then
echo "start recording"
./gone.sh
exit 1
elif [[ $action == *"stop"* ]]
then
echo "stop recording"
./gone.sh
exit 1
else
#More stuff done here
fiWhen I run this script manually the output is the following:19/01/2016 19:07:11
start
start recordingIf the same script is run via a (root) cronjob, the output is the following:19/01/2016 19:07:01
startAs you can see, the file "action.txt" has been read without a problem ("start" is logged both times) so this should not be an issue of permissions or wrong paths. But when run as a cronjob, the if-statement is not called. No "start recording" appears.So my question is: Why does the if-statement work when I call the script manually, but not when this is done via cron?
|
if statement not working in cron
|
You'll need several entries:Every 15 min during office hours*/15 09-18 * * * yourscript.shSend email only to manager, add an if inside the script that will check for the hour and send only to the manager00 06-09,18-23 * * * yourscript.shSend every three hours00 00,03,06 * * * yourscript.shFor not running on holidays, cron will not be able to help, you will need to get from a different source a file which lists all the holidays and then add an if inside your script.#!/bin/sh
if [ grep -q `date +%F` /random_location/holidays.txt]; then
exit 0
fi
# Continue your script from here
|
I wrote a shell script for monitoring a Rest API, when it is down the shell script send two mails one for the developer and the other for the manager. The problem is that I need to this with this frequency:Runs every 15 min during office hours (9-18 hours) during working days and send mail to manager and developerEvery hour 6-9 pm and from 18 to 24h on working days runs and sends mail to manager.Runs every 3 hours from 00:00 to 6:00 every night and the holidays and send mail to manager¿How can I discard between holidays and work days?
|
Crontab, scheduled jobs, on holidays
|
If you are putting more than one values for any attributes. Put them in an array list. SO, the hour will be ['0-6','13-23']
|
I need to schedule a cron job for daily running every 30 mins from 0 to 6 and from 13 to 23. I tried this code:cron { "MyJob":
ensure => present,
command => "my-cron-command",
user => 'root',
hour => "0-6,13-23",
minute => '*/30',
environment => "MY_ENV"
}This fails with0-6,13-23 is not a valid hourWhathourformat should I use? Do I need any other changes in cron clause?
|
Puppet: cron schedule - "is not a valid hour" error
|
Each cron job runs when it's scheduled to run, regardless of whether any other cron jobs happen to be running.Just make a cron job that executes several commands sequentially:* * * * * command1; command2; command3The command (in this casecommand1; command2; command3) is executed by/bin/sh(or by a shell you can specify by settingSHELLin your crontab)./bin/sh, or any shell worthy of the name, knows how to execute commands sequentially.If there are a lot of commands you can put them into a shell script and execute that fromcron.
|
I have a lot of php-scripts which I would like to execute as cronjob. It´s important that those scripts are executed in the right order and are not running at the same time. How can I set up cronjobs which run after each other?
|
Cronjobs after each other
|
Setting up cron on your serverUsecrontab -eto edit your cron jobs. To run a daily cron, add a line like this:0 3 * * * /bin/sh /path/to/magento/cron.shThis will run at 3 AM every night.For log cleaning, you can check/path/to/magento/shell/log.php.Set up cron in MagentoIn the Magento admin, go to: System > Configuration > Advanced > System > Cron (Scheduled Tasks) and configure cron jobs you wish to run.You should know that Magento runs cron jobs even if you don't have a daily cron job configured. Whenever Magento receives a request, it checks if there are any cron jobs to be run. Therefore, having the daily cron job would only make sense if you had no requests for an entire day.Really there is no next step to be done. I recommend you readHow to Set Up a Cron Job.
|
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.Closed10 years ago.Improve this questionCan someone please explain me, what I have to do?
I want Magento to clean logs, create a sitemap every day.Is this the right order:Setup Cron in ServerSetup Cron in MagentoWhat will be next step?How do I do step 1 and 2?
What will be step 3? Do I have to wait?
|
How to set up a cron job in Magento [closed]
|
Advantages of acronjob:You more easily have control over when it runs. You control the minute, hour, day, etc, that it will executeIt's easier to write the code and to manage its operation. It eliminates the looping and timing logic in the task, and you runcrontabto change the timing or shut it off.It's not occupying memory in your system when it's not running.If it fails and exits for some reason, it will start up again when the proper time comesAdvantages of the infinite loop:It doesn't have the overhead of being restarted every time it's neededI think the pros/cons regarding CPU real time and memory are probably slight in this specific case. But I prefer acronjob for anything that's going to run for an indefinite period of time because of the control over when it executes and ease of administration.
|
We coded a scheduled job in an infinite loop with a 120 second sleep. The scheduled task is a ping on a website to get a tiny bit of data. What are the advantages/disadvantages of using a cron job over our solution?
|
What are pros/cons of cron job over an infinite loop running?
|
The AndroidAlarmManageris the class you are looking for. It can trigger an intent to be sent to your application at set intervals so you can run any task you would like.
|
I want make a "Cronjob" that works in the backend and start all 30 Mins a methode. If the function return true (or someting else) the "Cronjob" create a Status-Bar-Notification.Is that possible in Android?
And when yes, with which function?Thank you very much.
|
Android Java - Creating a Cronjob
|
You should probably change the working directory to "leaf folder".Try this in your crontab command:cd /path_to_script; perl script.pl >/dev/nullWrt. log files. Cron will mail you the output. But since you sent stdout to /dev/null, only stderr will be mailed to you.If you want the output saved in a log file, then pipe the stderr/stdout output of the script into a file, like so:cd /path_to_script; perl script.pl 2>&1 >my_log_file
|
I have a Perl script which I want to run every 4 hours through cron. But somehow it fails to execute through cron and runs fine if I run it through command line. Following is the command which I set in crontab:perl -q /path_to_script/script.pl > /dev/nullAlso, when I run this command on command prompt, it does not execute but when I go in the leaf folder inpath_to_scriptand execute the file, it runs fine.Also, where will the log files of this cron job be created so that I can view them?
|
How to set a crontab job for a perl script
|
Just make a shell script which doespython a.py && python b.py && python c.pyThe&&in bash is for chaining commands consecutively, e.g. hereb.pywould only execute ifa.pycompleted successfully (i.e. returned 0).Save it in a file with no extension (some version of cron won't use.shfiles, I found this out the long and frustrating way), then put the location of that shell script in your cron table usingcrontab -e. There is plenty of information onsuperuserabout how to schedule cron jobs, so I recommend to search there for this information rather than here on SO (which is more about programming).
|
How can I automate running of 3 python scripts. Suppose, I have 3 scripts say a.py,b.py and c.py.Here a.py runs a web crawler and saves it as a xml file. Now b.py parses the xml file generated and saves as a pickle file. Now c.py inserts the list from pickle file to database.Is there a way to automate this?
|
how to automate running a python script
|
I think what you're after is a main+delta index. The main index you build say once a day then every 5 minutes (or whatever period you need) you'd update it with changes since the last time it built. There is something in the docs that explains this and there are also posts on Google about this as well.http://sphinxsearch.com/docs/current.html#delta-updatesIn terms of the cronjob to rebuild your delta every 5 minutes you'd want something like:*/5 * * * * /opt/sphinx/bin/indexer -c /opt/sphinx/etc/sphinx.conf --rotate delta_idx
|
I'm trying to figure out how I should be reindexing Sphinx. I'm using v 0.9.9, so I don't have the ability to do real-time updates of the index.I think I read somewhere that this can be done using a cron job, and that the index does not need to be entirely rebuilt (so no stopping the daemon). That said, I've never written nor run any cron jobs, so no idea where to even start.Any thoughts?
|
How to reindex Sphinx with MySQL
|
You probably need to pass ssh the -i argument to tell ssh to use a specific key file. The problem is that your environment is not set up to tell ssh which key to use.The fact that you're using python here is a bit of a red herring.
|
I'm running a script from crontab that will just ssh and run a command and store the results in a file.The function that seems to be failing issubprocess.popen.Here is the python function:def _executeSSHCommand(sshcommand,user,node):
'''
Simple function to execute an ssh command on a remote node.
'''
sshunixcmd = '/usr/bin/ssh %s@%s \'%s\'' % (user,node,sshcommand)
process = subprocess.Popen([sshunixcmd],
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
process.wait()
result = process.stdout.readlines()
return resultWhen it's run from the command line, it executes correctly, from cron it seems to fail with the error message below.Here are the crontab entries:02 * * * * /home/matt/scripts/check-diskspace.py >> /home/matt/logs/disklog.logHere are the errors:Sep 23 17:02:01 timmy CRON[13387]: (matt) CMD (/home/matt/scripts/check-diskspace.py >> /home/matt/logs/disklog.log)
Sep 23 17:02:01 timmy CRON[13386]: (CRON) error (grandchild #13387 failed with exit status 2)I'm going blind trying to find exactly where I have gone so wrong. Any ideas?
|
subprocess.popen seems to fail when run from crontab
|
QuartzQuartz is a full-featured, open source
job scheduling system that can be
integrated with, or used along side
virtually any J2EE or J2SE application
- from the smallest stand-alone application to the largest e-commerce
system. Quartz can be used to create
simple or complex schedules for
executing tens, hundreds, or even
tens-of-thousands of jobs; jobs whose
tasks are defined as standard Java
components or EJBs. The Quartz
Scheduler includes many
enterprise-class features, such as JTA
transactions and clustering.
|
Which is the best way to run a process in scheduler. I can either do it crontab or Spring-Batch. Any other better option?
|
java scheduler
|
+50Sure, I would love to explain the concept:>is for redirect/dev/nullis a black hole where any data sent, will be discarded2is the file descriptor for Standard Error>is for redirect&is the symbol for file descriptor (without it, the following 1 would be considered a filename)1is the file descriptor for Standard OutTherefore>/dev/null 2>&1is redirect the output of your program to/dev/null. Include both the Standard Error and Standard Out.cronwill only email you if there is some output from you job. With everything redirected tonull, there is no output and hencecronwill not email you.Hope I explained it more clearly.
|
From browsing the web I've noticed two variations for the command to initiate the WordPress cron jobs from cPanel.Please could someone explain the difference and which is the correct/best option to use?wget -qO- https://www.mydomain.co.uk/wp-cron.php &> /dev/nullwget -q -O - https://www.mydomain.co.uk/wp-cron.php?doing_wp_cron >/dev/null 2>&1Thanks
|
Wordpress CRON job commands
|
A CronJob has just another Pod underneath.When a Cronjob with a concurrency policy of "Replace" is still active, theJob will be deleted, which also deletes the Pod.When a Pod isdeletedthe Linux container/s will be sent aSIGTERMand then aSIGKILLafter a grace period, defaulted to 30 seconds. TheterminationGracePeriodSecondsproperty in aPodSpeccan be set to override that default.Due to theflagadded to theDeleteJobcall, it sounds like this delete is only deleting values from the kube key/value store. Which would mean the new Job/Pod could be created while the current Job/Pod is still terminating. You could confirm with a Job that doesn't respect aSIGTERMand has aterminationGracePeriodSecondsset to a few times your clusters scheduling speed.
|
I couldn't find anything in the official kubernetes docs about this. What's the actual low-level process for replacing a long-running cron job? I'd like to understand this so my application can handle it properly.Is it a cleanSIGHUP/SIGTERMsignal that gets sent to the app that's running?Is there a waiting period after that signal gets sent, so the app has time to cleanup/shutdown before it potentially gets killed? If so, what's that timeout in seconds? Or does it wait forever?For reference, here's theReplacepolicy explanation in the docs:https://kubernetes.io/docs/tasks/job/automated-tasks-with-cron-jobs/Concurrency PolicyReplace: If it is time for a new job run and the previous job run hasn’t finished yet, the cron job replaces the currently running job run with a new job run
|
What does shutdown look like for a kubernetes cron job pod when it's being terminated by "replace" concurrency policy?
|
I had a very similar issue with attempting to run a node.js script using crontab in MacOS. In order for me to finally get it to work, I had to addcronandzshto the Full Disk Access in my Security and Privacy settings in System Preferences.How to add cron:
1. Apple Menu -> System Preferences -> Security & Privacy -> Full Disk Access
2. Click the Lock to Allow Changes
3. Click the + Sign
4. hit Command + Shift + G and in type '/usr/sbin/'
5. scroll to find "cron" in the list of binaries
6. Click "Open"How to add zsh:
1. repeat steps 1 - 3
2. hit Command + Shift + G and in type '/bin'
3. scroll to find "zsh" in the list of binaries
4. Click "Open"After I did that my cron jobs ran without issue. Hope that helps
|
So I have a Python script which just pulls information from APIs and sends an email. When I run it manually, it works. I have a cron job set up:30 7 * * * /Users/myname/anaconda3/bin/python3 /Users/myname/Desktop/repo/somefolder/script.py >> /Users/myname/Desktop/filename.log 2>&1but the output in filename.log is:
/Users/myname/anaconda3/bin/python3: can't open file '/Users/myname/Desktop/repo/somefolder/script.py': [Errno 1] Operation not permittedI've tried lots of different things involving trying out different file permissions, creating the cron job as root, adding a shebang, and different Python paths, but cannot get any output other than this error. Nothing I've found online has given a different result so far.I'm using macOS Catalina 10.15.1.
The file permissions currently for my script:-rwxr--r-- 1 myname staff 4161 13 Nov 18:07 /Users/myname/Desktop/repo/somefolder/script.pyAny help would be appreciated!
|
Trying to run a Python script with cron, getting [Errno 1] Operation not permitted
|
+50I guess, instead of specifying the wday (Friday=5), you'll just have to specify the months where the 13th is a Friday; so, for 2019:0 0 13 9,12 * : do stuff, but avoid black catsOr, eternally more elegant, create a small script:$> cat /home/me/bin/test_friday_13
#!/bin/bash
if [ "$(date +'%A %d')" != "Friday 13" ]
then
exit 1
else
: do stuff, but avoid black cats
exit 0
fiand make the crontab entry:0 0 13 * * /home/me/bin/test_friday_13The script approach has the added benefit that you can run it from the command line. (Note: do not forget to alter the weekday name in the script to reflect your environment.)
|
I have seenthisquestion which indicates that the relationship between thewdayandmdayfields of a CRON schedule is an OR relationship. Say for example I want to schedule something for every Friday the 13th.Rather than the expected result, the CRON0 0 13 * 5will give me all Fridays of every month, as well as every 13th of every month.Is there any way to avoid this behavior and specify an AND relationship? (There seems to be mention of older versions using an AND relationship, however I would prefer to use a single tool with the ability to do both)
|
CRON with AND relationship between mday and wday
|
This can be achieved usingscheduler events. Check out this simplified example adapted from the documentation (not tested, but should work):def execution_listener(event):
if event.exception:
print('The job crashed')
else:
print('The job executed successfully')
# check that the executed job is the first job
job = scheduler.get_job(event.job_id)
if job.name == 'first_job':
print('Running the second job')
# lookup the second job (assuming it's a scheduled job)
jobs = scheduler.get_jobs()
second_job = next((j for j in jobs if j.name == 'second_job'), None)
if second_job:
# run the second job immediately
second_job.modify(next_run_time=datetime.datetime.utcnow())
else:
# job not scheduled, add it and run now
scheduler.add_job(second_job_func, args=(...), kwargs={...},
name='second_job')
scheduler.add_listener(my_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)This assumes you don't know jobs' IDs, but identify them by names. If you know the IDs, the logic would be simpler.
|
I'm using APScheduler(3.5.3) to run three different jobs. I need to trigger the second job immediately after the completion of first job. Also I don't know the completion time of first job.I have set trigger type as cron and scheduled to run every 2 hours.One way I overcame this is by scheduling the next job at the end of each job. Is there any other way we can achieve it through APScheduler?
|
APScheduler:Trigger New job after completion of previous job
|
-59/5 9 * * 1-5 <command>
0-30/5 15 * * 1-5 <command>
*/5 10-14 * * 1-5 <command>Try it (like in your comments) with three separate tabs.
|
I have read the answers and I am not able to get an explanation whether this expression will work:*/5 930-1530 * * 1-5 <command>I am trying to run a script every 5 minutes between 9:15AM to 15:30PM only on weekdaysNew tocronandubuntuThanks in advance.
|
Run a cronjob every 5 minutes on weekdays between 9:30AM to 15:30PM?
|
Your export command is okay and does not cause the asterisks to be expanded. The problem is yourecho $TEST. The rules for POSIX shells cause the expansion of$TESTto occur before glob expansion. So what you are doing is actually this:echo 30 *If you quote the expansion to inhibit the glob expansion you will see what you expect:echo "$TEST"Your question is a good example why the POSIX 1003 shell behavior is awful. And so many new, innovative, shells like fish and elvish don't implement that behavior.
|
I have a cron job environment variable which I wanna export.export CRON="30 * * * * *"The problem is * (asterisk) brings all file name in that folder. Which end up with an error.
For a quick try and understand the issue do followings.Open terminal (I am using Mac)export TEST="30 *"echo $TESTCheck the outputHere Output will not30 *It's30and all your files in that folder.PS:- This environment variable is getting read by one application and needs to use this in some function.
ex :-cron.schedule(CRON, function(){// some code handling})
|
How to export variable which includes * (asterisk) sign in it?
|
I found out what the problem was. @UweMannl was right all along. After @mhawke pointed out that cron's environment is different than the one of my terminal, I thought that perhaps also the python binary could be different and indeed it was: I want/home/ziofil/anaconda3/bin/pythonand cron was using/usr/bin/python.I modified the last line of the script to/home/ziofil/anaconda3/bin/python script_30_mins.pyand everything works!
|
I'm executing a python script every 30 minutes with cron, but it stops at the import statement and I don't understand why because I don't get any feedback.In my crontab I have*/30 * * * * sh exec_script.shThe fileexec_script.shiscd /home/ziofil/python_scripts
python script_30_mins.pyIn the python script I haveimport logging
logging.basicConfig(filename="explicit_log.txt",level=logging.DEBUG)
logger = logging.getLogger(__name__)
logger.debug("script is executed")
# in the python_scripts folder there is a subfolder utilities/ that
# contains utility_1.py, were I define the class Utility
from utilities.utility_1 import Utility
logger.debug("Utility loaded")
utility = Utility()
logger.debug("object creation")
utility.do_your_thing()
logger.debug("done its thing")If I executepython script_30_minutes.pyfrom the terminal, everything works just fine, but with cron the execution stops at theimportstatement (I read "script is executed", but noting else).What is going wrong?UPDATE: I put the import statement in atry/exceptblock and it logged the exception: "No module named utilities.utility_1". I also tried to set the PYTHONPATH variable in the shell script to/home/ziofil/python_scripts, but it still doesn't work.
|
python script stops at import statement when script is run as cronjob
|
Hasura suggests two ways to deploy and run Cron jobs.Cron microserviceHasura already has a microservice to run Cron jobs.If you already have a Hasura project run:hasura microservice create mycron --template=python-cronChangemycronto whatever you want to name your microservice. This will create a custom Python microservice designed to run Cron jobs. (Follow further instructions as prompted byhasuraCLI)To deploy this on Hasura, git commit and push to your cluster's remote.$ git add .
$ git commit -m "Add cron job"
$ git push hasura masterTo know more about how to customize this microservice, you can read thedocs.Kubernetes Cron jobsSince, Hasura runs on Kubernetes and Kubernetes (>= v1.8) already providesCron Jobsas a first class resource, it is recommended to use Kubernetes Cron jobs wherever possible.If you havekubectlinstalled you can check your Kubernetes version by running:kubectl version. In the output, the "server version" shows the version of the Kubernetes cluster. If you are running Kubernetes >= v1.8, we recommend you to use Kubernetes Cron jobs.When using Kubernetes Cron jobs, you can version control your cron job specs inside your Hasura project, and use thekubectltool to create and manage them.
|
How can I create, deploy and run and manageCron jobson Hasura?
|
How to create cron jobs on Hasura?
|
Maven DependencyPart ofSpring Context<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springframework.version}</version>
</dependency>Configuration to enable SchedulingReference from Documentationimport org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling
public class MyAppConfig {
//..
}Method to fire on the Cron you specifiedReference from Documentation// 0/15 -> Every 15 minutes on the clock
// 17-20 -> Between 5pm and 8pm on the JVM timezone
// if you want timezone specific there is a 'zone' parameter: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/Scheduled.html#zone--
@Scheduled(cron="0 0/15 17-20 * * ?")
public void doSomething() {
// ..
}DocumentationSpring Documentation on SchedulingSpring BootSpring Boot example of setup to run for the above cron
|
I need set upspring scheduled timeto be executed every 15 minutes from 5 p.m till 8 a.m, how to specify such expression? And also I'd like task be executed on weekdays not just MON-FRI, but according to my implementation of isBusinessDay logic.
|
How can I configure Spring Scheduled Task to run in a time range with specific delay?
|
You are telling it to execute on every hour, the correct CRON value for midnight only is0 0 0 * * ?Edit: The resource you used is from 2009 so I can see how this would be wrong, for reference the current CRON is "Seconds Minutes Hours Day-of-Month Month Day-of-Week Year (optional field)"
|
I implement a schedule in MVC app to run job in every day midnight. This is the code.IScheduler sched = container.Resolve<IScheduler>();
sched.JobFactory = new AutofacJobFactory(container);
sched.Start();
IJobDetail job = JobBuilder.Create<ProcessInvoiceJob>()
.WithIdentity("job1", "group1")
.Build();
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("trigger1", "group1")
.WithCronSchedule("0 0 * * * ?")
.Build();
sched.ScheduleJob(job, trigger);I read few articles and it contains cron expression for 12 midnight is "0 0 * * * ?"Eg :http://blog.bobcravens.com/2009/10/an-event-based-cron-scheduled-job-in-c/The issue is my schedule executes inevery one hour... How to fix this?
|
Cron Scheduler every day at 12 midnight
|
Try the following:crontab -r
crontab /var/spool/cron/crontabs/multi(edit) I believe in Java, you can call these this way:Runtime.getRuntime().exec("crontab -r");
Runtime.getRuntime().exec("crontab /var/spool/cron/crontabs/multi");First one removes the existing crontab. Second one installs the new crontab. And then you can verify by doing:crontab -l
|
I am writing a cron job to my crontab file using following java codePrintWriter writer = new PrintWriter("/var/spool/cron/crontabs/multi","UTF-8");
String cronTabString="25 13 * * * sudo wget --tries=0 \"https://some-url.com:7443/DataUpdater/updateChildren?folderId="+folderId+"&clientId="+clientId+"&clientSecret="+clientSecret+"&refreshToken="+refreshToken+"&deptName="+deptName+"\"";
writer.println(cronTabString);
writer.close();The code is successfully writing to cron tab file . But it does not run . My question is that is it even possible to execute a cron job in this manner ? According to me it is a valid cron tab entry , so it should get executed . Am i missing something here ?
|
writing a cron job prgrammatically to crontab file does not run
|
You can run the specific cronjob by following command.
For example:php bin/console sw:cron:run Shopware_CronJob_ClearHttpCacheBut it's only possible since Shopware 5.1.6, not as Shopware says since 5.1.5.
|
I'm new in shopware.I want to call cron job function programmatically is there any way ?I have tried following for call function using command line but getting too many argument error.php bin/console sw:cron:run ACTION-NAME
php bin/console sw:cron:run NAME -fI need one more help is use shopware function out side of shopware my custom file. is it possible ?Thanks in advance.
|
manually call cron job action programmatically in shopware
|
You need to specify the filepath as one path, not as directory and filename:#!/usr/local/bin/python2.7Otherwise, the directory path is considered as an executable.UPDATEAs Kevin Guan suggested, you can also use/usr/bin/envinstead of specifying the full path of the executable.#!/usr/bin/env python2.7
|
I have the following crontab set up in a CentOS VPS:SHELL=/bin/bash
HOME=/
* * * * * /root/ebay/findcheapitems.pyThe script runs fine manually using:python2.7 ebay/findcheapitems.pyIt has been run through dos2unix for EOL conversion, has -rwxr-xr-x permissions, and first line of the file has:#!/usr/local/bin python2.7However I am getting mail every time the cron job attempts to run, saying:/bin/bash: /root/ebay/findcheapitems.py: /usr/local/bin: bad interpreter: Permission deniedI've confirmed the location of python2.7 using 'which':# which python2.7
/usr/local/bin/python2.7I'm a linux beginner so I'm sure I'm missing something simple!
|
Python cron job: /usr/local/bin: bad interpreter: Permission denied
|
the short answer: it simply killed itself!my answer explained:
if you let a command get started by a crond it'll be executed in a subshell. most probably the line you'll find in ps or htop will look like this:/bin/sh -c pkill -f script.sh >log 2>&1 ; rm lock >log 2>&1(details may vary. e.g. you might have bash instead of sh)the point is, that the whole line got one PID (process id) and is one of the command lines which pgrep/pkill is parsing when using the '-f' parameter. as stated in the man page:-f, --full
The pattern is normally only matched against the process name. When -f is set, the full command line is used.now your pkill is looking for any command line in your running process list, which somehow contains the expression 'script.sh' and eventually will find that line at some point. as a result of it's finding, it'll get that PID and terminate it. unfortunately the very same PID holds the rest of you command chain, which just got killed by it self.so you basically wrote a 'suicide line of commands' ;)
btw: i just did the same thing today and thats how i found your question.hope this answer helps, even if it comes a little latekind regards
|
I wanted to kill a process and remove a flag indicating that process is running. cron:00 22 * * 1-5 pkill -f script.sh >log 2>&1 ; rm lock >log 2>&1This works perfectly when I run it on terminal. But in crontab rm is not running. All I can think of is that whole line after -f flag is being taken as arguments for pkill.
Any reason why this is happening?Keeping them as separate cron entries is working. Also pkill without -f flag is running (though it doesn't kill process as I want pattern to be searched in whole command).
|
pkill with -f flag in crontab not running command after semi colon
|
For running multiple spider you can try this code:from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings
process = CrawlerProcess(get_project_settings())
process.crawl('testspider1', domain='domain1.com')
process.crawl('testspider2', domain='domain2.com')
process.crawl('testspider3', domain='domain3.com')
process.start()
|
I have multiple spider files in same project, each one is for different domains and using same pipelines and settings.My basic need is to automate the scrapy project via scheduler like cron (I am using windows machine).The scrapy project needs to run once per day. The results pipeline will save the data to Mysql.Can anyone please suggest the appropriate way to fulfill my requirement.
|
Automate crawling of mutiple spiders in same scrapy project with cron or some other scheduler
|
Check three things:What is the error in the mail from cron?Do not use tilde expansion. Use full path names.Does your script set aPATH? Because cronjobs do not inherit anyPATH.The last point is responsible for 99% of all cron surprises.
Use something likePATH=$(/usr/bin/getconf PATH)at the beginning of your script. To test it on the command line, run it with an empty environment, e.g./usr/bin/env -i /path/to/script.shAs long as that doesn't work, the cronjob won't.
|
I'm trying to use rsync to backup all files and directories on my server, not really everything, I want to exclude a few things so I do:/usr/bin/rsync -aAXh --exclude={"/dev/*","/proc/*","/sys/*","/tmp/*","/run/*","/mnt/*","/media/*","/lost+found"} /* /mnt/backupdirectoryIt works well and does exactly what it is supposed to do until I put it in a cron job to do it everyday.30 23 * * * ~/scripts/backup_system.sh > ~/scripts/logs/backup_system.log 2>&1When executed as a cron job, it doesn't exclude all the directories it is supposed to exclude. I don't understand why. Couldn't someone explain to me why?I don't think it matters much but the system in use is Ubuntu Server 14.04.The problem was pointed out in the answer below. The use of braces in cron is not valid and I had to replace the previous command by:/usr/bin/rsync -aAXh --exclude=/dev/* --exclude=/proc/* --exclude=/sys/* --exclude=/tmp/* --exclude=/run/* --exclude=/mnt/* --exclude=/media/* --exclude=/lost+found /* /mnt/backupdirectory
|
rsync does not exclude extension when executed as a cron job
|
At least for the scheduling part, you could look intoWindows Azure Scheduler Serviceannounced not too long ago. Using this service, you would be able to invoke a HTTP/HTTPS web endpoint of write a message to a queue on a scheduled interval.For sending emails, you would still need to write a program. You could host this program as a cloud service running as a worker role or you could write that logic in a web application and host it as a Windows Azure Website.
|
Every day, I want to email all my users who have signed up, but not completed a specific task.What is the best framework for approaching this problem on the .NET MVC / Windows Azure platform?Coming from OS/Linux world I would write a program and schedule it to run daily via crontab.
|
Best practices for cron job style tasks on the ASP.NET MVC / Azure platform?
|
You can definitely make use ofcron4jfor cron expessions and scheduling.also you might find this post fromchiraginteresting,cronTrigger.getExpressionSummary()
Example:
CronTrigger t = new CronTrigger();
t.setCronExpression("0 30 10-13 ? * WED,FRI");
System.out.println(""+t.getExpressionSummary());
Output:
seconds: 0
minutes: 30
hours: 10,11,12,13
daysOfMonth: ?
months: *
daysOfWeek: 4,6
lastdayOfWeek: false
nearestWeekday: false
NthDayOfWeek: 0
lastdayOfMonth: false
years: *
|
I am looking for a cron expression library in java. Something that can parse cron expressions and return me future fire times for the trigger.API on the lines of.CronExpression cronExpression = new CronExpression("0 30 4 * * *");
List<Date> fireTimes = cronExpression.getFireTimes(todaysDate, nextWeekDate);I don't want to use something as complicated as quartz. The purpose is to basically use cron like a regex for timings. That's all. I do not want a background scheduler.I tried googling but wasn't able to find anything very helpful. Any suggestions would be appreciated.Regards,
PulkitP.S - I looked at using the CronExpression class out of quartz. Wasn't very helpful - failing some tests.
|
cron library for java
|
Remove the .sh extension from the script in/etc/cron.dand it will be called.run-partsignores files with a period in the name, so the .sh extension is preventing your script from running.Fromman cron-Files must conform to the same naming convention as used by run-parts(8): they must consist solely of upper- and lower-case letters, digits, underscores, and hyphens.
|
I very very rarely use Linux and so don't have any experience with bash scripts and cron jobs.
This is in fact my first attempt. So it's probably something really simple to fix.I have the following:/etc/cron.d/clear-mixtape-dir.sh
permissions are: 644#!/bin/bash
# Clears the /tmp/mixtape2 directory
rm -rf "/tmp/mixtape2/"*My crontab file looks like so:SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/
*/15 * * * * /etc/cron.d/clear-mixtape-dir.sh >/dev/null 2>&1I'm trying to execute the .sh script every 15 minutes.Everything i've found says this should work, but it doesn't.Does anything like file permissions (on files within /tmp/mixtape2/) matter in this case?
Or perhaps the permissions set on the actual .sh script - maybe they need setting to executable?Any advice appreciated.
|
Crontab not executing bash script
|
Check out:http://railscasts.com/episodes/206-action-mailer-in-rails-3for sending mail andhttp://railscasts.com/episodes/164-cron-in-ruby-revisedfor using whenever to set up a cron to call your mailerEDIT: Just saw your comment. In that case I would look at using something like resque-scheduler or the equivalent with sidekiq:https://github.com/bvandenbos/resque-schedulerthen you can do things like this:Resque.enqueue_at(24.hours.from_now, SendFollowUpEmail, :user_id => current_user.id)sidekiq example:FollowUpEmailer.perform_in(24.hours.from_now, current_user.id)
|
In my rails application, users can subscribe to some events. I'd like to send a mail to the user 24 hours before the begining of the the event.I'm not sure how to implement that. A rake task ? Is there some gems or some best practices to follow ?Thanks!EDIT:I guess that my cron must be run every minute to get each event that starts in 24 hours. But if the cron stops, or it takes more than a minute, I can't skip some emails. In the other way, how can I be sure I'm not sending the same email twice ?
|
Sending automatic mails in a Rails app
|
Here is a sample sh file running a test job#!/bin/bash
export JAVA_HOME=/usr/java/jdk1.6.0_07
echo "Java Home is $JAVA_HOME"
export CLASSPATH=.:..:$CLASSPATH:
echo "Path is is $PATH"
echo "CLASSPATH is is $CLASSPATH"
$JAVA_HOME/bin/java TestJob
echo "$JAVA_HOME/bin/java TestJob"then point to it from your cronjob like so0 5 * * * . $HOME/.profile; /path/to/command/test/job
|
How can I write a cron job start from scratch to run a java class or write a cron job class with embedded Java code to run?and how can I set the timer to run every one minute (for example) that cron job?Note: totally beginner with Linux
|
Write a simple cron job to run a Java class
|
Use the--evalargument tomongo. e.g./usr/bin/mongo --eval "db.clickreferrerurls.remove()"
|
I want to rundb.clickreferrerurls.remove()command for mongodb from crontab by defining cron job at local machine.How I could do this?
|
Define cron for mongodb table removing
|
9 * * 1-5 comand
Minute Hour Day Month Weekday
|
I am new to cron jobs, and I wanted to create a cron job which will not run on weekends, like Monday to Friday once in a day at 9:00AM. I am not sure about the format. Any suggestion or help please.thanks
|
CPanel Cron Job settings for working days
|
You can update the MAILTO variable to your email address, and cron should email you any STDOUT and STDERR output. Also check your syslog file /var/log/messages to see if the script is being executed by cron.-Tony
|
I'm using Ubuntu Linux 10.0.4. I want to run a script every 6 hours, every day. When I issuesudo crontab -e, I see:# m h dom mon dow command
* 00,06,12,18 * * * /opt/scripts/selenium/run_nis_inf_tests.shHowever, I'm not seeing the expected outcome from my script, and I'm not even sure if its running. Is there a way to test, short of waiting until the specified time, that the script is running properly. Or, how can I view the errors the script is generating? - Dave
|
How to test a cron job?
|
Well I've found out that it's running as no one, asget_current_user_id()returns 0
|
I'm writing a plugin. It has some job to be execute by wp_cron. Now within the script, it create/edit some posts automatically. So which user will be running the cron job?Also I notice it failed when callingWP_Filesystem()
|
Wordpress Cron: Running as which user?
|
I have a hunch that it's due to the waycronhandles stdout. How are you redirecting output?Fromhttp://aplawrence.com/BDD/bbcronbasics.html:OUTPUTNormally the output of any program is
sent to STDOUT (standard out) and
usually winds up on someone's display
screen. For jobs started by cron,
STDOUT will be directed to the local
mail subsystem, which means any output
generated by a cron job will be mailed
to the user owning the job. If this
is not desirable you should take steps
to redirect your cron job's output to
a file. It is also suggested you
redirect STDERR (standard error) to a
file so as to be able to analyze any
anomalies in your cron job's
execution.
|
I have a 'long' python script that takes roughly 45[min] to run. I use another (a 'scheduler' script) python script to run this long script. When I run the 'scheduler' script using the terminal, everything works perfectly (meaning, the 'long' script runs without any issues).I had some struggles, but eventually succeeded adding the 'scheduler' script to run through cron every minute. so it now 'runs' other script and works OK.Here is the problem: whenever a script (that is being 'run' by the 'scheduler') has a line that says:print "hello"or any 'print' statement, the cron job runs, but terminates after 20-30 seconds. When I remove any 'print' statements, cron runs the jobs normally and does not terminate.I'd like to fix this situation, and have the scripts continue to run even if they have some 'print' statements in them. any hints how to do it?P.S. from within the 'scheduler', I usesubprocess.Popen([sys.executable, command])to 'run' all other python scripts.
|
Cron Terminates Python Script?
|
Well, just made a cronjob in Scheduler, and took a look at my crontab file, and it looked like this:0 0 * * * ls >/dev/null 2>&1 # JOB_ID_1Notice theJOB_ID_1at the end.I went into~/.gnome/gnome-scheduler/, looked at the files there, and there was one named just1(as in the number "one") which had a bit of info, including the namever=3
title=Hello
desc=
nooutput=1So, I made a second cronjob:0 0 * * * ls -al >/dev/null 2>&1 # JOB_ID_2Copied the file1to2to match theJOB_ID_2, changed the description, making the file as:ver=3
title=This is a test
desc=
nooutput=1Then I switched over to Gnome-Schedule, and it had added the cronjob, and had the name updated.Follow the same steps, and you should be able to manually name any cronjob you want
|
How do you create a cron job from the command line, so that it shows up with a name in gnome-schedule?I know how to create a cron job using crontab. However, all my jobs show up with a blank name. I'd like to better document my jobs so I can easily identify them in gnome-schedule, or similar cron wrapper.
|
Creating a Named Cron Job
|
Some services (Friendfeed is a good example) are granted access to theTwitter Streaming API, aka the 'firehose'. It requires approval and a written agreement.
|
The webapps that depend on the public timeline of twitter, how often do they collect the data? There must be hundreds of thousands of messages every minute, correct? How do they manage to collect all the tweets, without missing any of them?
|
How often to run the cron, to mine twitter public timeline?
|
Your confusion may be because you expect Airflow to schedule DAGs like cronjob when it's not.
The first DAG Run is created based on the minimumstart_datefor the tasks in your DAG. Subsequent DAG Runs are created by the scheduler process, based on your DAG’sschedule_interval, sequentially. Airflow schedule tasks at theENDof the interval (Seedocs) you can view thisanswerfor examples.As for your sample code - never set yourstart_dateto be dynamic. It's a bad practice that can sometimes lead to DAG never being executed becausenow()always moves tonow() + intervalmay never be reached see AirflowFAQ.
|
How can I configure airflow (mwaa) so that it will fire at the same time (6am PST) every day regards of when the dag is deployed?I have tried what makes sense to me:set the schedule_interval to0 6 * * *.set the start date to:now = datetime.utcnow()
now = now.replace(tzinfo=pendulum.timezone('America/Los_Angeles'))
previous_five_am = now.replace(hour = 5, minute = 0, second = 0, microsecond = 0)
start_date = previous_five_amIt seems that whenever I deploy by setting the start_date to 5am the previous day it would always fire at the next 6am no matter what time I deploy the dag or do a airflow update
|
Airflow schedule_interval and start_date to get it to always fire the next interval
|
Network services almost never expose actual paths on the server's hard disk drive and even if they could it isn't a behaviour you can rely on. So the fact that your file is located at/admin/stock_update.phpin the FTP server doesn't say much about actual location on disk, which is what local command-line utilities expect.In PHP, you can find path on disk of current file with the__FILE__magic constant. You can create a test script:<?php
var_dump(__FILE__);... upload it to the same FTP location and execute through the web server. If that's not an option because files in your FTP account in not visible from the web you can run the file from cron and check the email.
|
I've just set up my first cron-jon to run a stock script every night.
Running it manually works fine.It's stored in /admin/stock_update.phpThe command i'm running is/usr/bin/php -q /admin/stock_update.phpBut I'm getting emails saying no input file is specified?
Any ideas?Cheers
|
cPanel cron job, no input file specified?
|
Thesetxkbmapcommand depends on the$DISPLAYenvironment variable to specify the X display it will affect.On my system, if I run it without setting$DISPLAY, I get:$ setxkbmap fr
Cannot open display "default display"Crontab does not set$DISPLAYfor the jobs it runs. In fact it provides only a minimal set of environment variables (on my system, just$HOME,$LOGNAME,$PATH,$LANG,$SHELL, and$PWD).Anything a command prints tostdoutorstderrwill normally be e-mailed to the owner of the crontab. You're likely to have an e-mail message on your system containing an error message similar to the above.It's likely that X Windows isn't even running yet when crontab executes the@rebootjob. You'll have to find another way to run that command automatically, or just run it manually. (Or there could be another way to do this that I haven't thought of.)
|
I want to execute a script once my computer boots up with cron.
But it doesn't work.My OS is Ubuntu MATE 16.04 LTS.My crontabMy scriptMy script's absolute pathOnce my Odroid boots up, the keyboard is still in qwerty.What am I doing wrong ?EDIT:I tried@reboot echo "hi" > /home/valery/reboot.txt 2>&1It works so the issue is not in the @reboot job.EDIT: SOLUTIONI run my script from System > Preference > Personal > Startup Applications
It's working fine.
|
Running Script at boot using Cron
|
There is no anything out of box but you can do something like this:// every hour
$schedule->command('get:twitter')->hourly();
// every one and a half hours
$schedule->command('get:facebook')->cron('0 0,3,6,9,12,15,18,21 * * * *');
$schedule->command('get:facebook')->cron('30 1,4,7,10,13,16,19,22 * * * *');
// every two hours at x.15 minutes (0.15, 2.15, 4.15 etc)
$schedule->command('get:googleplus')->cron('15 */2 * * * *');
|
I have three schedule job every hour in Kernel.php like below:$schedule->command('get:twitter')->cron('* 1 * * * *');
$schedule->command('get:facebook')->cron('* 1 * * * *');
$schedule->command('get:googleplus')->cron('* 1 * * * *');I want to run this three schedule in some time interval like below:$schedule->command('get:twitter')->cron('* 1 * * * *');//after 1 hour
$schedule->command('get:facebook')->cron('30 1 * * * *');//after 1.30 hour
$schedule->command('get:googleplus')->cron('45 1 * * * *');//after 1.45 hourIs this possible in laravel 5.1
|
Schedule job in laravel time interval
|
Whythe cron syntax is different is not a question I can answer, but if all you're looking for is a means to convert from unix to quartz syntax,https://github.com/jmrozanec/cron-utilshas helped me in the past.As far as I know, matching a given date time to a cron syntax is not exactly a simple task, because cron implies a certain frequency of repetition, where as a date/time is a moment in time.If you're trying to schedule a job to execute once, I suggest using a simple trigger.If you really want a cron job that executes on some schedule, the above cron-utils library, combined with a cron trigger should do the trick.Implementations of both triggers (and more) can be found here:http://www.quartz-scheduler.org/api/2.2.1/index.html
|
I want to check if given DateTime matches unix cron format or not. I was trying to use Quartz, but Quartz doesn't support "Day of Month" and "Day of Week" are both "*".For example:0 * * * * * (which means run every minutes) is not supported in Quartzbecause it must be0 * * * * ? or 0 * * ? * *.Can someone tell me why and also tell me how can I match a given DateTime to Unix cron format?Thanks
|
Java quartz scheduler: convert unix cron format to quartz cron format
|
Annotation parameters cannot be set dynamically. You can do it programmatically, like thisclass Scheduler implements Runnable {
public Scheduler(TaskScheduler scheduler, String timezone, String cron) {
scheduler.schedule(this, new CronTrigger(cron, TimeZone.getTimeZone(timezone)));
}
@Override
public void run() {
//
}
}
|
How can I use @Scheduled annotation of spring dynamically?CronTrigger(String expression, TimeZone timeZone)http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/support/CronTrigger.html#CronTrigger-java.lang.String-java.util.TimeZone-As I have multiple timeZones in database, how can I pass them dynamically?I tried this in my code:TimeZone timezone = null;
String timezone1 = null;
public SchedulerBean(String timezone2)
{
this.timezone1 = timezone2;
//constructor
}
@Scheduled(cron="0 0 8 * * ?", zone =timezone.getTimeZone(timezone1) ) //Error at this line
public void sendQuestionNotif()
{
//......code
}Here is theerrorI am getting,*Type mismatch: cannot convert from TimeZone to String*Please help me. Because I want to triggercronbased ontimezones. TIA.
|
Spring @Scheduled annotation
|
Just in case you are still looking at this in 2018, docs have changed, you can find DailyCronJob docs here:https://developers.whmcs.com/hooks-reference/cron/#dailycronjobAlso here you can find an entry point for modules creation in WHMCS:https://developers.whmcs.com/modules/
|
I created anaddonforwhmcsinwhmcs/modules/addonsdirectory which I want to run it by the system'scronjob.
WHMCS'scronjob uses this:php -q /var/www/html/whmcs/whmcs/admin/cron.phpto automate module functions (suspension, termination) and billing settings.Any ideas to add function to automate my addon using the samecronjob whilecron.phpis encrypted?
|
WHMCS how to add function to the system's cron job?
|
my guess is that yourcron.shis not executable and that's why nothing is happening.
Please check the file persmission and add the executable flagchmod +x /home/fpl/webapps/magento/cron.shYou might also want to check your server's log files for cron (e.g.https://askubuntu.com/questions/56683/where-is-the-cron-crontab-log)Instead of relying on the fact that cron is executable you could also run it like this/bin/bash /home/fpl/webapps/magento/cron.shAnd: instead of writing down the minutes like that you should be using this:*/5 * * * * /bin/bash /home/fpl/webapps/magento/cron.sh
|
I noticed the cron jobs not working because some tasks were not performed (automatic feed generation, google sitemap, ...).1) I installed the (very useful) AOE scheduler2) I've checked cron_schedule SQL table via PHPmyAdmin: no task is generated, but if I press Generate schedule in AOE scheduler, a list of task is generated. All tasks remain in pending status (executed at NULL).3) I've set (crontab -e)
0,5,10,15,20,25,30,35,40,45,50,55 * * * * /home/fpl/webapps/magento/cron.shI've tried to run cron.sh manually via SSH. When I run manually the sh the heartbeat task is run. So I'm also sure the problem is not in the cron.sh script.Cron is properly running on the server.ConfigurationWebfaction hosting
Magento ver. 1.8.0.0Cron schedule Configuration on magento admin panel
Generate Schedules Every 1
Schedule Ahead for 20
Missed if Not Run Within 15
Heartbeat task schedule (cron syntax) 0,5,10,15,20,25,30,35,40,45,50,55 * * * *Thanks for your help!
|
Magento Cron not working: no heartbeat task
|
If you dig deep enough, the log entry is actually DEBUG not ERROR or anything.0.1.0.1 - - [26/Jul/2014:17:55:58 -0700] "GET /device/alive HTTP/1.1" 404 87 - "AppEngine-Google; (+http://code.google.com/appengine)" "saslkdalskdn.appspot.com" ms=6 cpu_ms=0 cpm_usd=0.000010 ...
|
Right now I am only seeing this:I've checked my logs and couldn't find any reason for this failure.I've written test cases to verify that this query returns status code 200How can I find out what's causing this?
|
Appengine Cron job failed but no log whatsoever
|
Yes you can configure the threadCount property on Quartzsscheduler thread pool:org.quartz.threadPool.threadCountCan be any positive integer, although you should realize that only
numbers between 1 and 100 are very practical.This is the number of
threads that are available for concurrent execution of jobs.If you
only have a few jobs that fire a few times a day, then 1 thread is
plenty! If you have tens of thousands of jobs, with many firing every
minute, then you probably want a thread count more like 50 or 100
(this highly depends on the nature of the work that your jobs perform,
and your systems resources!).
|
I'm planning to use the Quartz cron scheduler for scheduling jobs. My scheduling pattern might require multiple jobs (say A, B, C) to be able to run at the same time (say every 10 minute both A and B should run in parallel). Right now, the way I see it Quartz seem to limit this functionality. I use Spring Framework.Question - Can schedules created/ implemented usingQuartz Cronbe able to run multiple jobs at the same execution time?Thanks!
|
Can Quartz Scheduler (cron) schedule multiple jobs at the same execution time?
|
It turned out to be an authentication problem. I solved it by adding the following two lines to the CURL configuration:curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);Hope it helps someone.
|
I have a very simple PHP script that is supposed to make a POST request. The code is the following:$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
mail('[email protected]','Script run with success','Script run with success',$headers);When I execute it from the browser, it works fine. However, when I try to execute it as a cron job the Curl part won't work. The rest of the script works even as a cron job, as I receive the confirmation email at the end.Here's the cron entry:*/5 * * * * /usr/bin/php /home/username/scripts/test.phpAny clue regarding why Curl is not executing as a cron job?Update:I tried to run the script via shell and the Curl part failed to run too. So:Browser: curl worksShell: curl doesn't workCron: curl doesn't workUpdate 2:Adding -dsafe_mode=Off while running via shell make the script run fine. However adding the same flag to the cron entry didn't do anything. So I still need to figure out how to make it work from cron.
|
PHP Curl script works from browser, doesn't work as Cron Job
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.