Response
stringlengths 8
2k
| Instruction
stringlengths 18
2k
| Prompt
stringlengths 14
160
|
---|---|---|
17
Even though the question was posted a while ago, I just had the same problem but found a solution (based on Kissaki's answer, thanks!) and thought I'd post it here for anyone still looking for a possible solution.
Prerequisites:
SSH access
Python
Code (python):
from subprocess import call
import time
while True:
call(["php","cron.php"])
time.sleep(120)
Share
Improve this answer
Follow
edited May 23, 2017 at 12:09
CommunityBot
111 silver badge
answered Feb 25, 2015 at 0:15
KJdevKJdev
72311 gold badge99 silver badges2020 bronze badges
2
So I need to call the python script over ssh once ?
– ledawg
Oct 28, 2016 at 11:17
Correct. If you have support for "screen", you could do it in the background as well.
– KJdev
Oct 28, 2016 at 11:29
Add a comment
|
|
Cron Jobs are closed on my server and server admin doesn't accept open it. Because , cron jobs slowing server etc. So, i need an alternative.
I have to run a php file (cron.php) every 2 minutes.
So, how can i do this ?
|
Are There Any Cron Jobs Alternative?
|
1
That error comes usually from lack of disk space.
I would do some more researching on this subject, by adding some logs before and after the tar execution.
Also check what user your configuration is using for the cron job you have running the backup. It can be some quota limit on that user as well, that doesn't happen when you run on the console outside cron.
Ask your provider for quota limits on the VPS for users and for processes... That is what rings the bell here.
Share
Improve this answer
Follow
answered Aug 28, 2015 at 7:38
prcprc
86077 silver badges1616 bronze badges
1
And if at all possible, check what user the cron job runs under, and run from the command line using that same user. The cron user might be chroot-jailed into a VFS with very little free space in the temporary directory, or things like that.
– LSerni
Mar 2, 2017 at 19:30
Add a comment
|
|
I have a PHP console script that is called via cron which itself among other things creates a tar file of a directory.
When calling the PHP script via cron the the tar file is not created correctly. The following error is given when viewing the tar file:
gzip: stdin: unexpected end of file
tar: Unexpected EOF in archive
tar: Error is not recoverable: exiting now
When calling the PHP script manually via console the tar file is created correctly. The cron log output shows no errors.
Here the tar call form the PHP script.
exec("cd $this->backupTempFolderName/$id; tar -czf ../../$this->backupFolderName/$tarFileName $dbDumpFileName documents");
Dose anybody have an idea why the tar is created correctly when manually called and fails when called via cron?
Update: The error given while creating the tar file via cron is:
tar: ../../backup/20150819-060003.tar.gz: Wrote only 4096 of 10240 bytes
tar: Error is not recoverable: exiting now
Sometimes the error is:
tar: ../../backup/20150819-054002.tar.gz: Cannot write: Broken pipe
tar: Error is not recoverable: exiting now
As said before, the when executed via cron the tar file is created, but always 50% of the correct size (when manually executing the script):
-rw-r--r-- 1 gtz gtz 1596099468 Aug 19 06:25 20150819-042330.tar.gz <- Manually called skript, working tar
-rw-r--r-- 1 gtz gtz 858570752 Aug 19 07:21 20150819-052002.tar.gz <- Script called via cron, broken tar
Update 2
After doing some further research based on the input given here, might should add that the cron called script is running on a virtual private server - I suspect that some limitations may exist for cron jobs that are not documented by the hoster (only limit on minimum repetition time is given in the docs).
|
Tar error: Unexpected EOF in archive when running via Cron/PHP
|
46
I had the same issue. But, finally I solved it by running the following command.
sudo apt-get install php7.0-curl
Restart the server after installing. This answer may not be useful for the user who asked because he asked it two months ago. But, this may be useful for the users who reading this in the future.
Share
Improve this answer
Follow
edited May 9, 2017 at 5:41
answered Feb 4, 2014 at 14:59
SriramanSriraman
7,76655 gold badges4141 silver badges6060 bronze badges
2
Weird, I had done this with the initial install but maybe it needed to be done separately? Whatever.
– Jacksonkr
Mar 7, 2017 at 18:42
Update, since this is still a top question: sudo apt install php7.0-curl
– DannyB
Apr 27, 2017 at 15:20
Add a comment
|
|
I'm trying to set up a cronjob which requires curl, and I'm calling it directly from crontab with
* * * * * /usr/bin/php myurl/my_cron.php
The problem is, it looks like the curl module isn't installed for my phpcli.
It works just fine when I hit the url from my browser, but when I run
php -q myfile.php
from the command line, it returns
PHP Fatal error: Call to undefined function curl_init() in my_cron.php on line 20
When I run php -m the curl module does not show up. However when I go to the browser and dump the php_info(), the module shows up and says its correctly installed.
The other kicker is i've been trying to install curl with apt-get onto the server (Ubuntu 12.04 php 5.4), it seems to take down my PHP as it begins to simply attempt to download the index.php file wherever I try to browse to.
Here are the attempts I've made to install curl that have taken down PHP:
sudo apt-get install php-curl
sudo apt-get install curl libcurl3 libcurl3-dev php5-curl
After each of these I restarted the apache2 server and still no dice, it attempted to download the file instead of opening the page.
How can I install php5-curl to just the cli, so that my server can run it and I don't have to go through a browser?
The other possibility is I could run the cronjobs through wget from the crontab file, but I've heard that's not the best option and potentially unreliable.
Any help is much appreciated. Thanks!
|
Installing curl to PHP cli
|
Use wildcard. And just put it in your crontab use the crontab -e option to edit your crontab jobs.
See example:
* * * * * find /path/to/*.log -mtime +7 -exec rm -f {} \;
Just to increment the answer check this nice article on how to work with your crontab ! in Linux .
|
Hi. I want to remove all log files from the last 7 days from a folder, but leave all the other files. Can I use the below command? How do you specify that it just delete the files with .log extension?
find /path/to/file -mtime +7 -exec rm -f {} \;
Do I need to write this command into some file, or can I just write it in command prompt and have it run automatically every day?
I have no idea how to run a cron job in linux.
|
Remove log files using cron job
|
A Java library that converts cron expressions into human readable strings: https://github.com/RedHogs/cron-parser
|
Closed. This question is seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. It does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I am using Quartz with Java to schedule jobs. One thing is that i store cron expressions on a database and i would like to present them to a user but in a more readable form. So i was wondering if there is a utility that could convert a cron expression into a human readable string. Something like :
""0 30 10-13 ? * WED,FRI"
will become
"Fires at 10:30, 11:30, 12:30, and 13:30, on every Wednesday and Friday."
|
Cron to human readable string [closed]
|
When wget runs, by default, it generates an output file, from what I need to remember.
You probably need to use some option of wget, to specify to which file it should write its output -- and use /dev/null as destination file (It's a "special file" that will "eat" everything you can write to it)
Judging from man wget, the -O or --output-file option would be a good candidate :
-O file
--output-document=file
The documents will not be written to the appropriate files, but all will be concatenated together and written to file.
so, you might need to use something like this :
wget -O /dev/null http://www.example.com/your-script.php
And, btw, the output of scripts run from the crontab is often redirected to a logfile -- it can always help.
Something like this might help, about that :
wget -O /dev/null http://www.example.com/your-script.php >> /YOUR_PATH_logfile.log
And you might also want to redirect the error output to another file (can be useful, to help with debugging, the day something goes wrong) :
wget -O /dev/null http://www.example.com/your-script.php >>/YOUR_PATH/log-output.log 2>>/YOUR_PATH/log-errors.log
|
I have a php script I want to run every minute to see if there are draft news posts that need to be posted. I was using "wget" for the cron command in cPanel, but i noticed (after a couple days) that this was creating a blank file in the main directory every single time it ran. Is there something I need to stop that from happening?
Thanks.
|
Cron job creating empty file each time it runs
|
I think that you should check
/etc/default/cron
or just type
Crontab cronfile
and you should find
TZ=UTC
This should be changed (for example America/New_York). Second way is set in cron example
5 2 3 * * TZ="America/New_York" /do/command > /dev/null 2>&1
|
Is there a way of setting up a cronjob for a specific timezone?
My shared hosting is in USA (Virginia) and I am in UK. If I set a cron job to be executed at 1600 hrs every friday, then it will execute when its 1600 in Virginia.
I was wondering if I can setup my cronjob in such a way that it understands which timezone to pick. I am not too worried about daylight saving difference.
I have asked my shared hosting providers about it and they said I should be able to set the timezone in some cron ini files, but I could not find any.
|
Cron job in a different timezone
|
The difference is that the crontab command is the interface provided by the system for users to manipulate their crontabs. The /etc/crontab file is a special case file used to implement a system-wide crontab. /var/spool/cron/crontabs/$USER (or whatever the path happens to be) is an implementation detail.
If you can schedule jobs using the crontab command, you should do so.
Manually editing the contents of /etc/crontab (a) requires root access, and (b) is more error-prone. You can mess up your system that way.
If the jobs are to be run under your own user account, there's no need to use root access.
Even if the jobs are to run as root, it probably still makes more sense to use the crontab command invoked from the root account. (For one thing, it should detect syntax errors in the file.)
Personally, I don't use crontab -e. Instead, I have a crontab file that I keep in a source control system, and I use the crontab filename form of the command to install it. That way, if I mess something up, it's easy to revert to an earlier version.
|
What is the difference when I put crontab entry in crontab -e (the default location is : /var/spool/cron/username ) and in /etc/crontab? I mean crond daemon will essentially execute both cron jobs. Then why there are two different ways to schedule cronjob ? Which one preferred over the other ?
|
cronjob entry in crontab -e vs /etc/crontab . Which one is better?
|
TinyPNG uses pngquant.
Pngquant has option to set desired quality, similar to JPEG. You can run something like:
<?php system('pngquant --quality=85 image.png'); ?>
Pngquant website has example code showing how to use pngquant from PHP.
For JPEG you can apply lossless jpegcrush.
JpegMini (commercial) and jpeg-archive (free) are lossy and can can automatically find a minimal good quality for a JPEG.
In PHP you can roughly estimate how much JPEG was compressed by observing how much file size changes after re-compression. File size of JPEG recompressed at same or higher quality will not change much (but will lose visual quality).
If you recompress JPEG and see file size halved, then keep the recompressed version. If you see only 10-20% drop in file size, then keep the original.
If you're compressing yourself, use MozJPEG (here's an online version).
|
I'm wondering how to figure out the best compress rate (small filesize + no quality loss) automatically.
At the moment I'm using imagejpeg() with $quality = 85 for each .jpg.
PageSpeed (Chrome Plugin) suggests, to lower the quality of a few images to save some kb. The percentage of reduction is different.
I'd like to write a cronjob that crawls a specific directory and optimizes every image.
How does PageSpeed or TinyPNG figure out the best optimized quality and is this possible with PHP or another serverside-language?
|
PHP: How to compress images without losing visible quality (automatically)?
|
The only suggestion I would make is to make your exception handling a little more specific. You don't want to accidentally delete the fcntl import one day and hide the NameError that results. Always try to catch the most specific exception you want to handle. In this case, I suggest something like:
import errno
try:
fcntl.lock(...)
except IOError, e:
if e.errno == errno.EAGAIN:
sys.stderr.write(...)
sys.exit(-1)
raise
This way, any other cause of the lock being unobtainable shows up (probably in your email since you're using cron) and you can decide if it's something for an administrator to look at, another case for the program to handle, or something else.
|
I need to run a python script (job.py) every minute. This script must not be started if it is already running. Its execution time can be between 10 seconds and several hours.
So I put into my crontab:
* * * * * root cd /home/lorenzo/cron && python -u job.py 1>> /var/log/job/log 2>> /var/log/job/err
To avoid starting the script when it is already running, I use flock().
This is the script (job.py):
import fcntl
import time
import sys
def doIncrediblyImportantThings ():
for i in range (100):
sys.stdout.write ('[%s] %d.\n' % (time.strftime ('%c'), i) )
time.sleep (1)
if __name__ == '__main__':
f = open ('lock', 'w')
try: fcntl.lockf (f, fcntl.LOCK_EX | fcntl.LOCK_NB)
except:
sys.stderr.write ('[%s] Script already running.\n' % time.strftime ('%c') )
sys.exit (-1)
doIncrediblyImportantThings ()
This approach seems to work.
Is there anything I am missing? Are there any troubles I can run into using this approach?
Are there more advised or "proper" ways of achieving this behaviour?
I thank you for any suggestion.
|
Running python script with cron only if not running
|
43
Since cron runs jobs time-based, not interval-based, there's no blindingly simple way to do it. However, although it's a bit of a hack, you can set up multiple lines in crontab until you find the common denominator. Since you want a job to run every 72 minutes, it must execute at the following times:
00:00
01:12
02:24
03:36
04:48
06:00
07:12
...
As you can see, the pattern repeats every 6 hours with 5 jobs. So, you will have 5 lines in your crontab:
0 0,6,12,18 * * * command
12 1,7,13,19 * * * command
24 2,8,14,20 * * * command
36 3,9,15,21 * * * command
48 4,10,16,22 * * * command
The other option, of course, is to create a wrapper daemon or shell script that executes and sleeps for the desired time until stopped.
Share
Improve this answer
Follow
answered Apr 14, 2009 at 0:44
lc.lc.
115k2020 gold badges160160 silver badges187187 bronze badges
Add a comment
|
|
How would I get a cron job to run every 72 minutes? Or some not so pretty number like that?
|
How to do a cron job every 72 minutes
|
Because nodejs is single thread a while(true) will not work. It will just grab the whole CPU and nothing else can ever run.
nodejs will stay running when anything is alive that could run in the future. This includes open TCP sockets, listening servers, timers, etc...
To answer more specifically, we need to see your code and see how it is using node-cron, but you could keep your nodejs process running by just adding a simple setInterval() such as this:
setInterval(function() {
console.log("timer that keeps nodejs processing running");
}, 1000 * 60 * 60);
But, node-cron itself uses timers so it appears that if you are using node-cron properly and you correctly have tasks scheduled to run in the future, then your nodejs process should not stop. So, I suspect that your real problem is that you aren't correctly scheduling a task for the future with node-cron. We could help you with that issue only if you show us your actual code that uses node-cron.
|
I am creating NodeJS based crawler, which is working with node-cron package and I need to prevent entry script from exiting since application should run forever as cron and will execute crawlers at certain periods with logs.
In the web application, server will listen and will prevent from terminating, but in serverless apps, it will exit the program after all code is executed and won't wait for crons.
Should I write while(true) loop for that?
What is best practices in node for this purpose?
Thanks in advance!
|
prevent NodeJS program from exiting
|
Cron runs commands as they would be ran via the shell, so running PHP would use local paths.
You need to use a command like:
php /home/USER/public_html/cron.php
Or if including the query string is necessary, use cURL instead (if it's installed):
curl http://www.wetube.org/cron.php?id=01001
You might want to look at not exposing your cron scripts to the internet - move them to outside your web directory because if someone finds it they can constantly reload it to spam your cron scripts (i.e. sending lots of emails)
|
I have a E-mail schedule runs everyday on php page using cron jobs. The php code workds fine when i run the page using a link.
Now when I run the php script using cron jobs, it also works fine but when I put some query the cron jobs won't understand the link.
for example: http://www.wetube.org/cron.php?id=01001 so now if I try to run this everyday using cron job it's doesn't work.
But if we just erase the query it works fine. Do you guys know any code which makes this link work in cron job?
|
how to run php file using cron jobs
|
You should use the built-in task output method in Laravel.
For example:
$file = 'command1_output.log';
$schedule->command('command1')
->sendOutputTo($file);
|
Hi I'm running CRON JOB with Laravel
Function declaration in Laravel
protected function schedule(Schedule $schedule)
{
echo "test CRON JOB\n";
$file1 = '1.log';
$file2 = '2.log';
$schedule->command('command1')->sendOutputTo($file1);
$schedule->command('command2')->sendOutputTo($file2);
}
CRON JOB - Setting
pathToArtisan schedule:run 2>&1 >> /home/log/cron_output.log
Log file output (cron_output.log)
test CRON JOB
Running scheduled command: '/opt/alt/php55/usr/bin/php' 'artisan'command1 > '1.log' 2>&1 &
Running scheduled command: '/opt/alt/php55/usr/bin/php' 'artisan' command2 > '2.log' 2>&1 &
The echo in the function schedule is displayed but the ones inside my command 1 and command 2 are not.
I tried
echo "test"; $this->info('test');
No files 1.log or 2.log where created neither /home/log/ or where the Kernel.php file is or Command folder
Any ideas ?
Thank you
|
CRON JOB - LARAVEL - OUTPUT
|
There are four common causes for cron job commands to behave differently compared to commands typed directly into an interactive shell:
Cron provides a limited environment, e.g., a minimal $PATH, and other expected variables missing.
Cron invokes /bin/sh by default, whereas you may be using some other shell interactively.
Cron treats the % character specially (it is turned into a newline in the command).
The command may behave differently because it doesn't have a terminal available.
You must precede all % characters with a \ in a crontab file, which tells cron to just put a % in the command, e.g.
16 * * * * mysqldump myDB myTB > "/backup/ABCbc$(date +'\%d-\%b-\%Y-\%H-\%M').sql" 2> "/backup/ABCbc_errORS$(date +'\%d-\%b-\%Y-\%H-\%M').txt"
(As a separate matter, always put double quotes around a "$variable_substitution" or a "$(command substitution)", unless you know why not do it in a particular case. Otherwise, if the variable contents or command output contains whitespace or ?*\[, they will be interpreted by the shell.)
|
The following does work as expected:
date +'%d-%b-%Y-%H-%M'
28-Sep-2009-14-28
But none of the following 4 entries from crontab are working.
* * * * * date +\'%d-%b-%Y-%H-%M\' >> /backup/shantanu/testing.txt
* * * * * date +'%d-%b-%Y-%H-%M' >> /backup/shantanu/testing1.txt
* * * * * date +"%d-%b-%Y-%H-%M" >> /backup/shantanu/testing2.txt
* * * * * date +\"%d-%b-%Y-%H-%M\" >> /backup/shantanu/testing3.txt
Error:
/bin/sh: -c: line 0: unexpected EOF while looking for matching `"'
/bin/sh: -c: line 1: syntax error: unexpected end of file
I can save the same code in a shell script and set the cron, but I will like to know if it is possible to directly set a cron for the task.
The actual cron entry that I am trying to set looks something like this...
16 * * * * mysqldump myDB myTB > /backup/ABCbc$(date +'%d-%b-%Y-%H-%M').sql 2> /backup/ABCbc_errORS$(date +'%d-%b-%Y-%H-%M').txt
|
Cron fails on single apostrophe
|
0 0 0 * *
http://www.quartz-scheduler.org/documentation/quartz-1.x/tutorials/crontrigger
|
What is the Quartz cron trigger expression for batch job run at 00hr every day?
|
What is the expression for Quartz cron trigger to run at every day at 00hr?
|
The solution is to put this in schedule.rb:
env :PATH, ENV['PATH']
Here's a little guide I put together on the topic.
|
My ruby is in /usr/local/bin. whenever can't find it, and setting PATH at the top of my cron file doesn't work either, I think because whenever is running the command inside of a new bash instance.
# this does not work
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/sbin
# Begin Whenever generated tasks for: foo
0 * * * * /bin/bash -l -c 'cd /srv/foo/releases/20110429110637 && script/rails runner -e production '\''ActiveRecord::SessionStore::Session.destroy_recent(15)'\'''
# End Whenever generated tasks for: foo
How can I tell whenever where my ruby binary is? Making a symbolic link from /usr/bin seems messy to me, but I guess that might be the only option.
This question offers env :PATH, "..." in schedule.rb as a solution, but (a) I can't find any documentation of that feature anywhere in the docs (b) it doesn't seem to have solved the asker's problem (unfortunately it takes non-trivial turnaround time for me to just try it).
update actually it is in the bottom of this page, i'll try it now.
more info
I can't modify the cron command because it's generated by whenever
i verified that if I make a new bash shell with bash -l, /usr/bin/env finds ruby just fine
I just tried the exact command in cron, starting with /bin/bash, from the command line of that user, and it worked.
so, this is very mysterious...
|
Setting path for whenever in cron so it can find ruby
|
23
For Cron like tasks you have to use AlarmManager, this is a system service, for using it in your code you need to call:
AlarmManager myAlarmManager = Context.getSystemService(Context.ALARM_SERVICE).
Full docs about AlarmManager here.
Share
Improve this answer
Follow
answered Mar 10, 2011 at 23:10
Lucas S.Lucas S.
13.5k99 gold badges4747 silver badges4646 bronze badges
1
How to set repeating for alarm manager IF i have a cron expression?!
– Dr.jacky
May 11, 2015 at 13:17
Add a comment
|
|
The last time this question was asked (by a different user), the answer response was:
If this is in a running activity, you could use Timer/TimerTask and a Handler, or you could use postDelayed() and an AsyncTask.
Here: Android Repetitive Task
I am still learning how to program android. I have gone through the skills I do know including threads and had many issues with my code. Can anyone give an example of how to use: time/timertask and handler OR postDelayed() and AsyncTask.
|
Android regular task (cronjob equivalent)
|
29
crontab only expects one command.
If multiple commands are to be executed, they can be bundled using bash -c
* * * * * bash -c 'ls -t /mytest | tail -n +2 | xargs rm --'
Share
Improve this answer
Follow
edited May 26, 2019 at 8:18
answered May 26, 2019 at 8:13
UtLoxUtLox
3,97422 gold badges1111 silver badges1313 bronze badges
2
Probably remove the explicit paths while you're at it.
– tripleee
May 26, 2019 at 8:17
is PATH at the beginning of crontab defined?
– UtLox
May 26, 2019 at 9:35
Add a comment
|
|
I need to delete files under directory except latest 2.
I have prepared command to list according to date and delete files. It work when I run manually from command line , however it does not work in crontab.
In crontab,
* * * * * /bin/ls -t /mytest | /usr/bin/tail -n +2 | /usr/bin/xargs rm --
This command works when I run this command from commandline.
Also tried to add command in bash script then called that script from crontab but it did not work again.
How can I run that command via crontab?
|
Bash command with pipe not working in crontab
|
15
On Windows OS there is no cron .... you need to use the scheduler task from Windows to create a "Cronjob". Example for using the windows scheduler
Share
Improve this answer
Follow
edited Oct 8, 2018 at 8:39
Nick
3,25222 gold badges2929 silver badges5252 bronze badges
answered Jul 3, 2013 at 7:28
donald123donald123
5,71733 gold badges2727 silver badges2323 bronze badges
1
@Jaak Kütt add another basic link
– donald123
Jun 17, 2015 at 10:15
Add a comment
|
|
Help needed to set up this command in my Xampp windows server
0 * * * * cd C:/xampp/htdocs/plugins/moviefeed/ && php cron.php
Could you please point me in the right direction
thanks
|
Setting Up A Cronjob In Windows Xampp
|
Yes, it does.
*/X means: every X minutes
* means: every minute
So all together */1 means exactly the same as *.
From man cron:
Step values can be used in conjunction with ranges. Following a
range with /number specifies skips of the number's value through
the range. For example, 0-23/2'' can be used in the hours field to specify command execution every other hour (the alternative in the V7 standard is 0,2,4,6,8,10,12,14,16,18,20,22'').
Steps are also permitted after an asterisk, so if you want to say
every two hours'', just use */2''.
|
As I have recently seen something like
*/1 * * * * ./script.py
I would like to know if it means the same as
* * * * * ./script.py
|
Is `*/1 * * * *` and `* * * * *` equivalent in CRON?
|
scheduler.getCurrentlyExecutingJobs() should work in most case. But remember not to use it in Job class, for it use ExecutingJobsManager(a JobListener) to put the running job to a HashMap, which run before the job class, so use this method to check job is running will definitely return true. One simple approach is to check that fire times are different:
public static boolean isJobRunning(JobExecutionContext ctx, String jobName, String groupName)
throws SchedulerException {
List<JobExecutionContext> currentJobs = ctx.getScheduler().getCurrentlyExecutingJobs();
for (JobExecutionContext jobCtx : currentJobs) {
String thisJobName = jobCtx.getJobDetail().getKey().getName();
String thisGroupName = jobCtx.getJobDetail().getKey().getGroup();
if (jobName.equalsIgnoreCase(thisJobName) && groupName.equalsIgnoreCase(thisGroupName)
&& !jobCtx.getFireTime().equals(ctx.getFireTime())) {
return true;
}
}
return false;
}
Also notice that this method is not cluster aware. That is, it will only return Jobs currently executing in this Scheduler instance, not across the entire cluster. If you run Quartz in a cluster, it will not work properly.
|
How to check if scheduled Quartz cron job is running or not? Is there any API to do the checking?
|
How to check whether Quartz cron job is running?
|
When you do crontab -e, try this:
59 23 * * * /usr/sbin/myscript > /dev/null
That means: At 59 Minutes and 23 Hours on every day (*) on every month on every weekday, execute myscript.
See man crontab for some more info and examples.
|
How can I set up my crontab to execute X script at 11:59PM every day without emailing me or creating any logs?
Right now my crontab looks something like this
@daily /path/to/script.sh
|
How to setup a crontab to execute at specific time
|
I think the problem is that cron is going to run your scripts in a "bare" environment, so your DJANGO_SETTINGS_MODULE is likely undefined. You may want to wrap this up in a shell script that first defines DJANGO_SETTINGS_MODULE
Something like this:
#!/bin/bash
export DJANGO_SETTINGS_MODULE=myproject.settings
./manage.py mycommand
Make it executable (chmod +x) and then set up cron to run the script instead.
Edit
I also wanted to say that you can "modularize" this concept a little bit and make it such that your script accepts the manage commands as arguments.
#!/bin/bash
export DJANGO_SETTINGS_MODULE=myproject.settings
./manage.py ${*}
Now, your cron job can simply pass "mycommand" or any other manage.py command you want to run from a cron job.
|
I want my custom made Django command to be executed every minute. However it seems like python /path/to/project/myapp/manage.py mycommand doesn't seem to work while at the directory python manage.py mycommand works perfectly.
How can I achieve this ? I use /etc/crontab with:
****** root python /path/to/project/myapp/manage.py mycommand
|
Django custom command and cron
|
This happens because you have a celery.py file in the same package as your settings.py, which shadows the global celery package.
To get around this, insert the following string at the beginning of the settings.py:
from __future__ import absolute_import
Hope it helps!
|
I am following the instructions here:
http://celery.readthedocs.org/en/latest/userguide/periodic-tasks.html#crontab-schedules
I'm supposed to be able to do the following: from celery.schedules import crontab
In my settings.py I have:
from kombu import serialization
serialization.registry._decoders.pop("application/x-python-serialize")
import djcelery
djcelery.setup_loader()
from celery.schedules import crontab
...
CELERYBEAT_SCHEDULE = {
'first_task': {
'task': 'apps.icecream.tasks.sync_flavors',
'schedule': crontab(minute='*/30', hour='1, 3, 6, 8-20, 22')
},
'second_task': {
'task': 'apps.robots.tasks.run_robots',
'schedule': crontab(minute='*/6')
}
}
However, I'm getting an error: "No module named schedules"
If I switch to the other way of scheduling, using timedelta, then everything is fine and I can get my periodic tasks to run:
CELERYBEAT_SCHEDULE = {
'first_task': {
'task': 'apps.icecream.tasks.sync_flavors',
'schedule': timedelta(minutes=30)
},
'second_task': {
'task': 'apps.robots.tasks.run_robots',
'schedule': timedelta(minutes=6)
}
}
Why can't I use the crontab approach?
|
django + celery - How do I set up a crontab schedule for celery in my django app?
|
16
I don't think cron expression will allow you to do that, but you can use
SimpleScheduleBuilder.repeatSecondlyForever( 25 )
as 300 (5 minutes) is a multiple of 25 it will repeat automatically.
Share
Improve this answer
Follow
answered Jun 7, 2011 at 18:56
rediViderrediVider
1,27622 gold badges1313 silver badges3030 bronze badges
Add a comment
|
|
I am using the Quartz Scheduling API for Java. Could you help me to run every 25 seconds using cron-expression. It's just a delay. It does not have to start always at second 0. For example, the sequence is like this: 0:00, 0:25, 0:50, 1:15, 1:40, 2:05, etc until minute 5 when the sequence begins again at second 0.
Thank you.
|
How to run every 25 seconds in Quartz scheduler?
|
you can provide to it a cron expression or rate. what you are looking for is the cron expression option that will let you to say when exactly to run.
more info - https://docs.aws.amazon.com/lambda/latest/dg/tutorial-scheduled-events-schedule-expressions.html
if you want to run it once, manually, you can always trigger it with the "test" button at the top of the page. you can really be creative here, for example, you can even trigger it with an http request that will allow you to integrate it to whatever you want, super easily (Invoke a AWS Lambda function by a http request)
|
I am aware of the CloudWatch recurring events that can be used to run Lambda recurringly.. but is there a way that I can trigger it on a certain time and not repeat?
|
How to trigger a Lambda function at specific time in AWS?
|
If you are using ZEO you can add the following to your Crontab to do this:
0 1 * * 6 <path-to-buildout>/bin/zeopack
If you don't want to do it manually, add this to your buildout.cfg and the crontab entry above will be added automatically when you run bin/buildout:
parts += crontab_zeopack
# pack your ZODB each Sunday morning and hence make it smaller and faster
[crontab_zeopack]
recipe = z3c.recipe.usercrontab
times = 0 1 * * 6
command = ${buildout:directory}/bin/zeopack
|
Looking at plone.org to find a way to periodically pack my instance's ZODB I could only find http://plone.org/documentation/faq/how-do-i-pack-the-zodb that doesn't talk about automated packs, but just manually initiated ones.
I know I can simulate the manual pack with wget or curl, but I'd like to know if that is the best practice in use for production sites.
|
What is the suggested way to cron-automate ZODB packs for a production Plone instance?
|
As said before, CLI scripts by default have no time limit.
But I would also like to mention an alternative to your cron job approach:
You can fork a CLI PHP script from a PHP script under webserver control. I have done this many times. It is especially useful if you have a script with long execution time which must be triggered by some website user action (e.g. building a very large archive file and send a download link by email when the file is complete).
I usually fork a CLI script from a webserver PHP script using the popen() function. This allows to nicely transfer parameters to the new script instance like this:
$bgproc = popen('php "/my/path/my-bckgrnd-proc.php"', 'w');
if($bgproc===false){
die('Could not open bgrnd process');
}else{
// send params through stdin pipe to bgrnd process:
$p1 = serialize($param1);
$p2 = serialize($param2);
$p3 = serialize($param3);
fwrite($bgproc, $p1 . "\n" . $p2 . "\n" . $p3 . "\n");
pclose($bgproc);
}
In the CLI script you would receive these params like this...
$fp = fopen('php://stdin', 'r');
$param1 = unserialize(fgets($fp));
$param2 = unserialize(fgets($fp));
$param3 = unserialize(fgets($fp));
fclose($fp);
...and do anything with them that would take to long under webserver control.
This technique works equally well in *nix and Windows environments.
|
I am coding a php script that does some back end stuff and needs to run every 8 hours or so. The script takes a while to execute. For the hell of it, I tried it from my browser and the connection to the server gets reset well before the script terminates. My question is - if I run it directly, ie. php -a file.php as a cron job, are there any internal time constraints on execution? This script may take 2-5 minutes to complete and cannot be interrupted. I've never done this before so I am not sure if php has quirks when running heavy scripts.
|
Running php script as cron job - timeout issues?
|
Day is the day of the month.
Weekday is the day of the week (0 and 7 == Sunday).
For you, you need:
<key>StartCalendarInterval</key>
<array>
<dict>
<key>Weekday</key>
<integer>1</integer>
<key>Hour</key>
<integer>8</integer>
<key>Minute</key>
<integer>0</integer>
</dict>
<dict>
<key>Weekday</key>
<integer>2</integer>
<key>Hour</key>
<integer>8</integer>
<key>Minute</key>
<integer>0</integer>
</dict>
<dict>
<key>Weekday</key>
<integer>3</integer>
<key>Hour</key>
<integer>8</integer>
<key>Minute</key>
<integer>0</integer>
</dict>
<dict>
<key>Weekday</key>
<integer>4</integer>
<key>Hour</key>
<integer>8</integer>
<key>Minute</key>
<integer>0</integer>
</dict>
<dict>
<key>Weekday</key>
<integer>5</integer>
<key>Hour</key>
<integer>8</integer>
<key>Minute</key>
<integer>0</integer>
</dict>
</array>
Not quite as elegant as cron...
|
I'm working with launchd to run some automated tasks, and I was wondering what the difference is between 'Day' and 'Weekday'.
According to http://discussions.apple.com/thread.jspa?threadID=1361809 there is a 'subtle' difference that can cause launchd to misbehave.
Ultimately, I'd like to have a plist that runs every weekday (Mon - Fri) at 8am, but I don't know how to get the cron equivalent of
0 8 * * 1-5
|
What's the difference between 'Day' and 'Weekday' in launchd StartCalendarInterval?
|
Windows doesn't have Cron (it is the main task scheduling program for Linux systems). The Windows version for that is the Task Scheduler. This question recommends using the at command.
So that Cron doesn't have anything to do with the Apache, Mysql, PHP setup I don't think it is possible to reliably test the cronjobs you created for the Linux Cron in windows (maybe with Cygwin).
|
How to test a cron job in Local Server like WAMP?
|
How to test a cron job in Local Server like WAMP?
|
Just add an expression @Scheduled(cron = "${some.profile.cron}") to swap the cron depending on selected profile.
|
I am using spring-schedule like this.
@Component
@EnableScheduling
public class ScheduledTasks {
@Autowired
private ISomeJob someJob;
/**
* do a Job every 5 minutes.
*/
@Scheduled(cron = "0 0/5 * * * ?")
public void foo(){
someJob.doSomething();
}
}
It worked. But there is a problem.
I have two profiles named debug and release.
I want do this job every 5 minutes in debug but per hour in release.
So is there any way to config the value of cron in application.properties.
|
How to config cron value of @Scheduled in application.properties
|
20
It can be done in a tricky sort of way.
You need three separate cron jobs for that range, all running the same code (X in this case):
one for the 29th and 30th of June ("0 7 29,30 6 * X").
one for every day in the months July through November ("0 7 * 7-11 * X").
one for all but the last day in December ("0 7 1-30 12 * X").
This gives you:
# Min Hr DayOfMonth Month DayOfWeek Command
# --- -- ---------- ----- --------- -------
0 7 29,30 6 * X
0 7 * 7-11 * X
0 7 1-30 12 * X
Then make sure you comment them out before June 29, 2010 comes around. You can add a final cron job on December 31 to email you that it needs to be disabled.
Or you could modify X to exit immediately if the year isn't 2009.
if [[ "$(date +%Y)" != "2009" ]] ; then
exit
fi
Then it won't matter if you forget to disable the jobs.
Share
Improve this answer
Follow
edited Apr 19, 2009 at 4:46
answered Apr 1, 2009 at 11:09
paxdiablopaxdiablo
866k239239 gold badges1.6k1.6k silver badges2k2k bronze badges
Add a comment
|
|
I want to be able to configure something like this.
I want to run job 'X' at 7 AM everyday starting from 29/june/2009 till 30/12/2009. Consider current date as 4/4/2009.
|
Does cron expression in unix/linux allow specifying exact start and end dates
|
You can use the basic cron. On debian or ubuntu you can do this:
crontab -e -u <username>
Where username is the name of the user that should execute the command.
In the editor add your command. Here is a good explanation how the line should look. For a Symfony2 command something like this should work:
* * * * * /usr/bin/php /var/www/symfony2/app/console your:command --option=123
This will execute your:command --option=123 every minute.
On a windows machine you can use the ac command. It is available for windows 7 by default. Read the docs here. It should look something like this:
AT 00:00 /every:M,T,W,Th,F "php /var/www/symfony2/app/console your:command --option=123"
Make sure that php is available globaly or the path to the php.exe file is correct.
|
I create a console command in my project. I want it to be executed everyday at 7 p.m. How could i do it in symfony2? A basic php cron job way or symfony2 have something more convenient?
Thanks
|
Cron Job in symfony2
|
6
Use the Quartz framework for that. It has a cron like syntax, can be clustered and only one of the hosts in the cluster will do one job at a time. If a host or job fails, another host will retry the pending job.
Share
Improve this answer
Follow
answered Nov 12, 2014 at 15:22
StefanStefan
12.2k55 gold badges4949 silver badges6767 bronze badges
3
1
Quartz is a pretty framework to do job scheduling, and it also supports distributed, while I want to know how Quartz's cluster is designed.
– coderz
Nov 12, 2014 at 15:24
2
coderz, quartz with cluster works like a simple quartz configuration would. you just set the org.quartz.jobStore.isClustered = true, add the quartz tables to the database and quartz will take care of the disaster tolerance and the run-only-once. For more info on how quartz clustering works you can read quartz-scheduler.org/generated/2.2.1/html/qs-all/#page/…
– Marios
Nov 13, 2014 at 8:15
Quartz(quartz-scheduler.org) is unnecessarily complex for a scheduler in terms of setup and infra. Dkron(dkron.io) doesnt do very well if the dkron server has a downtime. The best solution i have come across is temporal.io(temporal.io). It is a distributed cron scheduler and workflow orchestrator. Runs on docker as small as 500MB RAM t3a.nano via ECS with database supported by astra db (hosted cassandra). Temporal executes the schedules even when temporal itself has a downtime and picks up the crons it has missed during its downtime
– thehellmaker
Dec 3, 2022 at 5:18
Add a comment
|
|
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I want to design a job scheduler cluster, which contains several hosts to do cron job scheduling. For example, a job which needs run every 5 minutes is submitted to the cluster, the cluster should point out which host to fire next run, making sure:
Disaster tolerance: if not all of the hosts are down, the job should be fired successfully.
Validity: only one host to fire next job run.
Due to disaster tolerance, job cannot bind to a specific host. One way is all the hosts polling a DB table(certainly with lock), this guaranteed only one host gets the next job run. Since it often locks table, is there any better design?
|
How to design a distributed job scheduler? [closed]
|
14
Create a file touch ~/code-wait.sh:
#!/bin/bash
OPTS=""
if [[ "$1" == /tmp/* ]]; then
OPTS="-w"
fi
/usr/local/bin/code ${OPTS:-} -a "$@"
Make this file executable:
chmod 755 ~/code-wait.sh
Add to your .bashrc or .bash_profile or .zshrc:
export VISUAL=~/code-wait.sh
export EDITOR=~/code-wait.sh
Run command:
EDITOR='code' crontab -e
Share
Improve this answer
Follow
answered Dec 4, 2020 at 11:11
Dmitry GrinkoDmitry Grinko
14.5k1414 gold badges6464 silver badges8888 bronze badges
11
P.S: echo $SHELL - helps to check what shell you're using
– Dmitry Grinko
Dec 4, 2020 at 11:20
2
What does it do?
– fotoflo
Dec 24, 2020 at 3:56
It just helps you to use your vscode editor for editing a cron-job file
– Dmitry Grinko
Dec 24, 2020 at 7:07
4
But um... what does it do? it looks like it gets the other command line arguments and appends them somehow to the call to open vscode?
– fotoflo
Dec 26, 2020 at 23:15
2
I had to use /opt/homebrew/bin/code instead of /usr/local/bin/code. I am on macOS Sonoma and VSCode is installed with Homebrew. You can do #!/bin/bash
OPTS=""
if [[ "$1" == /tmp/* ]]; then
OPTS="-w"
fi
/usr/local/bin/code ${OPTS:-} -a "$@"
0 in order to get the path to #!/bin/bash
OPTS=""
if [[ "$1" == /tmp/* ]]; then
OPTS="-w"
fi
/usr/local/bin/code ${OPTS:-} -a "$@"
1 executable.
– Igor
Nov 7, 2023 at 17:38
|
Show 6 more comments
|
If I try to use Visual Studio Code (on macOS 10.15) to edit my crontab, it opens an empty file without the contents of my crontab.
$ VISUAL='code' crontab -e
crontab: no changes made to crontab
I didn't actually expect this to work (without -w) but include it for completeness. But when I add the -w it still fails.
$ VISUAL="code -w" crontab -e
crontab: code -w: No such file or directory
crontab: "code -w" exited with status 1
It occurred to me that there may be some weirdness with quoting, but neither single quotes nor the following fixed anything:
$ function codew() {
function> code -w "$1"
function> }
$ export VISUAL='codew'
$ crontab -e
The problem seems to be that the crontab's tempfile is not actually present. But how do I solve this? How can I use VS Code to edit crontabs?
|
How can I edit crontabs in VS Code?
|
The user has to be specified in the command and not in the file with the u parameter.
For more details on scheduling cron jobs using mysqldump, check this answer
|
I try to backup my database with mysqldump and cronjobs.
Well, I added the following command to the crontab of user root:
*/30 * * * * mysqldump -u root -pVERYSECUREPASSWORD --all-databases > /var/www/cloud/dump_komplett.sql &> /dev/null
This works fine so far, but the problem is that the password is set in this command.
So I want to include a .database.cnf file that look like this
[mysqldump]
user=root
password=VERYSECUREPASSWORD
and changed the mysqldump command to
mysqldump --defaults-extra-file="/var/crons/mysql/.database.cnf" --all-databases -u root > /var/www/cloud/dump_komplett.sql
to solve this problem.
But this command fails with the error:
mysqldump: Got error: 1045: Access denied for user 'root'@'localhost' (using password: YES) when trying to connect
I don't know what's wrong.
Here are some commands I also tried:
mysqldump --defaults-extra-file="/var/crons/mysql/.database.cnf" --all-databases > /var/www/cloud/dump_komplett.sql
mysqldump --defaults-file="/var/crons/mysql/.database.cnf" --all-databases > /var/www/cloud/dump_komplett.sql
mysqldump --defaults-file="/var/crons/mysql/.database.cnf" --all-databases -u root > /var/www/cloud/dump_komplett.sql
and .database.cnf contents I also tried:
[client]
user=root
password=VERYSECUREPASSWORD
[mysqldump]
host=localhost
user=root
password=VERYSECUREPASSWORD
[client]
host=localhost
user=root
password=VERYSECUREPASSWORD
|
Mysqldump without password in crontab
|
1
+50
Assuming you have sudo on the machine it's located on...
First check to see if it's located in the usual cron directories /etc/cron.*
sudo find /etc/cron* -mount -iname yiic
If nothing shows up there then search the entire filesystem because otherwise you'll start having to search a lot of other places manually and it takes more time than running a find
sudo find / -mount -iname yiic
In both find commands if the filename is or has ever been anything other than yiic do yiic* so that it searchs for anything that starts with yiic
Once you have found the copies, if there are any others, remove every single one except the newest one, or even that one and then reinstall the script on the machine from version control.
Edit:
Probably more than you really care about, but the find command breaks down like this:
sudo - elevated priviledges so you can search everywhere as opposed to where you're user can read
find - command to look for thigs
/ - the starting point for the search, can be anywhere
-mount - this tells find not to search other filesystems
-iname - case insensitive name to search for
yiic - the search term
Share
Improve this answer
Follow
edited Dec 22, 2015 at 18:27
answered Dec 22, 2015 at 17:43
LoganLogan
43944 silver badges1010 bronze badges
Add a comment
|
|
I'm working with Yii and have to implement a script for cron.
I've got a script file, which just calls Yii and starts my php-script file.
Until this point everything is fine. If I'm updating the php-script, Cron just continues executing the old one.
Restart of cron-service, reboot of the server etc didn't help.
I also uninstalled cron and installed it again, but nothing changed. He still executes the old version of this php-script.
Anyone an idea what's wrong or what I could do to solve this? I'm using Ubuntu 12.04.
EDIT:
The cronjob script is running:
#!/bin/bash
cd ../www/protected/ ./yiic Cron ProcessPayments
The php-script
class CronCommand extends CConsoleCommand {
public function actionProcessPayments() {
...
}}
This works, but any change I make on this script is ignored by Cron.
And now I'm on this point: he executes both. My old version and the new version. I've never been this confused by something.
|
Cron Job uses old non-existent php file
|
You could actually do it in PHP. Write one program which will run for 59 seconds, doing your checks every second, and then terminates. Combine this with a cron job which runs that process every minute and hey presto.
One approach is this:
set_time_limit(60);
for ($i = 0; $i < 59; ++$i) {
doMyThings();
sleep(1);
}
The only thing you'd probably have to watch out for is the running time of your doMyThings() functions. Even if that's a fraction of a second, then over 60 iterations, that could add up to cause some problems. If you're running PHP >= 5.1 (or >= 5.3 on Windows) then you could use time_sleep_until()
$start = microtime(true);
set_time_limit(60);
for ($i = 0; $i < 59; ++$i) {
doMyThings();
time_sleep_until($start + $i + 1);
}
|
I have a dedicated server running Cent OS with a Parallel PLESK panel. I need to run a PHP script every second to update my database. These is no alternative way time-wise, it needs to be updated every second.
I can find my script using the URL http://www.somesite.com/phpfile.php?key=123.
Can the file be executed locally every second? Like phpfile.php?
Update:
It has been a few months since I added this question. I ended up using the following code:
#!/user/bin/php
<?php
$start = microtime(true);
set_time_limit(60);
for ($i = 0; $i < 59; ++$i) {
doMyThings();
time_sleep_until($start + $i + 1);
}
?>
My cronjob is set to every minute. I have been running this for some time now in a test environment, and it has worked great. It is really super fast, and I see no increase in CPU nor Memory usage.
|
Run a PHP script every second using CLI
|
You can check org.quartz.CronExpression
It has a method named getNextValidTimeAfter which you can use.
|
I need to find out the first occurrence of Date and time represented by given cron expression.
Is there any java class, utility code which can help in getting data object from given cron expression ?
|
Is there any java class to get Date from cron expression
|
Tasks have been replaced with commands, which are the same thing in Laravel 4, but integrated with Symfony's console component, and even more powerful than before.
|
I'm trying to find out how to set up a cron job in Laravel 4, and the command I would need to run in artisan for it.
In Laravel 3, there were Tasks but these don't seem to be there anymore and there is no documentation as to how to do it...
|
Cron Job with Laravel 4
|
Since sys.stdin will be a TTY in debug mode, you can use the os.isatty() function:
import sys, os
if os.isatty(sys.stdin.fileno()):
# Debug mode.
pass
else:
# Cron mode.
pass
|
This question already has answers here:
Checking for interactive shell in a Python script
(5 answers)
Closed 6 years ago.
Imagine a script is running in these 2 sets of "conditions":
live action, set up in sudo crontab
debug, when I run it from console ./my-script.py
What I'd like to achieve is an automatic detection of "debug mode", without me specifying an argument (e.g. --debug) for the script.
Is there a convention about how to do this? Is there a variable that can tell me who the script owner is? Whether script has a console at stdout? Run a ps | grep to determine that?
Thank you for your time.
|
Detect if python script is run from console or by crontab [duplicate]
|
Just use the following cron:
@Scheduled(cron = "0 0/15 * * * *")
Spring cron expression syntax slightly differs from unix cron expression. One immediate difference - it supports 1 less field (6 rather than 7).
|
I tried to use cron expression from this site http://www.cronmaker.com/
@Scheduled(cron = "0 0/15 * 1/1 * ? *")
public void clearRps() {
}
But it throws: java.lang.IllegalStateException: Encountered invalid @Scheduled method 'clearRps': Cron expression must consist of 6 fields (found 7 in "0 0/15 * 1/1 * ? *")
|
Spring execute method every 15 minutes
|
39
I had the same issue, except that my script was ending with
interact
Finally I got it working by replacing it with these two lines:
expect eof
exit
Share
Improve this answer
Follow
answered Sep 13, 2012 at 9:38
cataccatac
40944 silver badges44 bronze badges
1
2
Thank you very much for this! I had to explicitly set the timeout with "set timeout 600", because the default timeout of 10s was too fast for the operation that I was doing.
– Pada
Mar 5, 2013 at 13:37
Add a comment
|
|
I have an expect script which I need to run every 3 mins on my management node to collect tx/rx values for each port attached to DCX Brocade SAN Switch using the command #portperfshow#
Each time I try to use crontab to execute the script every 3 mins, the script does not work!
My expect script starts with #!/usr/bin/expect -f and I am calling the script using the following syntax under cron:
3 * * * * /usr/bin/expect -f /root/portsperfDCX1/collect-all.exp sanswitchhostname
However, when I execute the script (not under cron) it works as expected:
root# ./collect-all.exp sanswitchhostname
works just fine.
Please Please can someone help! Thanks.
The script collect-all.exp is:
#!/usr/bin/expect -f
#Time and Date
set day [timestamp -format %d%m%y]
set time [timestamp -format %H%M]
#logging
set LogDir1 "/FPerf/PortsLogs"
et timeout 5
set ipaddr [lrange $argv 0 0]
set passw "XXXXXXX"
if { $ipaddr == "" } {
puts "Usage: <script.exp> <ip address>\n"
exit 1
}
spawn ssh admin@$ipaddr
expect -re "password"
send "$passw\r"
expect -re "admin"
log_file "$LogDir1/$day-portsperfshow-$time"
send "portperfshow -tx -rx -t 10\r"
expect timeout "\n"
send \003
log_file
send -- "exit\r"
close
|
Expect script does not work under crontab
|
Finally I have used CronExpression like this to schedule a recurring job with frequency of every 8 days or for any number of days for that matter.
string cronExp = "* * */8 * *";
RecurringJob.AddOrUpdate("MyJob",() => ScheduledJob(), cronExp);
The third segment in CronExpression represents day of month.
The respective segments are as follows - (Ref: https://en.wikipedia.org/wiki/Cron)
|
Is it possible to create a recurring job in Hangfire that executes after a given number of days, say 8.
The nearest I found was to execute a job once in a week -
RecurringJob.AddOrUpdate("MyJob",() => ScheduledJob(), Cron.Weekly());
Understanding that Hangfire also accepts standard CronExpression, I've tried exploring cron expression for this frequency but couldn't found one for it-
https://en.wikipedia.org/wiki/Cron
One ugly solution could be to create 3 or 4 jobs that executes once in month at some dates accordingly, but I don't want to do that.
Any suggestions please.
|
Execute a recurring job in Hangfire every 8 days
|
I just found this, using
grep -r "export MY_VAR" /
EDIT: Amazon seems to move the file location from time to time. Current location is:
/opt/elasticbeanstalk/support/envvars
So I think I'll just include (source [file path]) that in my script before calling my php script. Still seems like a funky way to do things. I'm still in for better solutions.
I was running PHP via bash script triggered by cron. So to setup the environment, I would do something like this:
#!/bin/bash
source /opt/elasticbeanstalk/support/envvars
php -f my-script.php
See @userid53's answer below for PHP solution.
|
I'm trying to run a PHP script that is triggered by a cron script (in cron.d). The script is triggered properly but it is missing the Elastic Beanstalk "Environment Variables" that are stored in the $_SERVER superglobal. The script is being run as the user "root" for now, but it's not in the same environment that has the environment variables. The variables are set correctly, if I run the script from a full shell it runs just fine.
Where are the "exports" for these variables? Where do they get set? I found the SetEnvs for Apache in /etc/apache/conf.d/aws_env.conf. I can't find anything in the user's .bashrc, .bash_profile, etc. Is there a workaround? A better way to do this?
Thanks.
|
AWS Elastic Beanstalk: Running Cron.d script, missing Environment Variables
|
A cronjob is a good option, but I didn't want it to happen automatically. I found a script that will notify you if a new version of a formula installed on your Mac is available.
I extended the script to not show pinned formulae in the notifier.
I decided to use a launchd-agent for the cronjb, because this also runs if Mac is started later. Cron-jobs just run if your mac is already on at that time.
For a comparison of cronjob vs launchd, I recommend reading this.
Here's my configuration which runs every day at 10am and 3pm. The script, called by the agent, is located at /usr/local/bin/homebrew-update-notifier.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>EnableGlobbing</key>
<false/>
<key>Label</key>
<string>homebrew.simonsimcity.update-notifier</string>
<key>ProgramArguments</key>
<array>
<string>/bin/bash</string>
<string>/usr/local/bin/homebrew-update-notifier</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/tmp/homebrew.simonsimcity.update-notifier.err</string>
<key>StandardOutPath</key>
<string>/tmp/homebrew.simonsimcity.update-notifier.out</string>
<key>StartCalendarInterval</key>
<array>
<dict>
<key>Hour</key>
<integer>10</integer>
<key>Minute</key>
<integer>0</integer>
</dict>
<dict>
<key>Hour</key>
<integer>15</integer>
<key>Minute</key>
<integer>0</integer>
</dict>
</array>
</dict>
</plist>
You will now be notified if a new update is available. Call brew upgrade if you feel outdated, or include it in the script.
|
I've been discvering some long lasting linux techs to help automate my daily work. I found cron to be very powerful if I can use it to check the updates of some packages I have on my system.
For example, I want to update my Homebrew everyday at 11pm. What I did is, with sudo crontab -u user -e, I opened up crontab in Vim. And I put following commands into it, to make updates for homebrew and send me an email.
Here's the code:
[email protected]
* 23 * * * brew update
and I save it to wait for magic happens. Instead of excuting this command, in the email I recieved, it says /bin/sh: brew : command not found
But when I type /bin/sh in terminal to open sh and type in brew update it will update the Homebrew0。
What did I do wrong with my Homebrew1 configuration?
Any help will be appreciated!
|
how to update homebrew with Cron on Mac os
|
It will work once every hour, exactly at x:00.
Keep in mind the format of crontab is:
+---------------- minute (0 - 59)
| +------------- hour (0 - 23)
| | +---------- day of month (1 - 31)
| | | +------- month (1 - 12)
| | | | +---- day of week (0 - 6) (Sunday=0 or 7)
| | | | |
* * * * * command to be executed
so 0 in the first position means every minute 0, any hour, and day.
|
0 * * * *
I use crontab. How often this is done in cron?
|
How often you do this in a cron? - 0 * * * *
|
For Last Sunday
echo date('Y-m-d',strtotime('last sunday'));
Edited Answer:
For Last Last Sunday
echo date('Y-m-d',strtotime('last sunday -7 days'));
|
I am using a cron job to generate weekly reports on my database. Basically, the report generation script is in PHP. I scheduled a daily cron job.
My week for the reporting starts on Sunday.
I only want the report generation script to generate report, for the previous week from previous Sunday through to previous Monday.
Take for example.
Today is 4 March 2013. When the script runs, it should generate the
report for 24 Feb 2013 to 3 March 2013. Tomorrow, when the script
runs, it should also only run the report for 24 Feb 2013 to 3 March 2013.
How can I get last Sunday's date, automatically in my script?
Currently, I hard code using the following:
$startDate = strtotime("13 January 2013");
$strStartDate = date ("Y-m-d 00:00:00", $startDate);
$strEndDate = date ("Y-m-d 23:59:00", $startDate + (6*24*60*60));
Any help is much appreciated. Thank you.
|
Get last Sunday date in PHP
|
If both are installed, all you need to do is run the script using the relevant PHP binary.
So for example:
// Runs using the PHP binary located at /usr/bin/php
* * * * * root /usr/bin/php -n "/path/to/script.php"
or
// Runs using the PHP binary located at /var/php5
* * * * * root /var/php5 -n "/path/to/script.php"
All you need to know is the full file system path of the PHP CLI binaries, and call the relevant one to run your code.
|
I am hosted with 1and1.com, and I have setup my files to be parsed with php5 using .htaccess.
But that only works in apache, and not in command line, which defaults to the server default php4.
So currently I can not setup cron jobs to run my code as php5. Any ideas?
|
How can I force PHP Version for Command Line?
|
Although I can not recommend this way, but if you really need to execute a Lambda function every 5 seconds, you can try this:
Create a Lambda function A which is executed every minute.
Create a Lambda function B which is triggered every 5 seconds by Lambda function A. (A triggers B, waits 5 seconds, triggers B, waits 5 seconds, ...)
Stop Lambda function A after approximately one minute. (You can read the remaining miliseconds from the context object => if you reach >55 seconds, stop execution)
Please carefully consider if you really need this.
|
My problem
I'd like to invoke an AWS Lambda function every 5 seconds, for some monitoring purposes.
According to the docs,
Rate frequencies of less than one minute are not supported.
What have I tried
STFW.
My Question
Can I autonomously invoke an AWS Lambda function every 5 seconds?
|
Invoking a Lambda function every 5 seconds
|
After many weeks of trying to resolve this error. The following fixes worked
Upgrade project from Laravel 5.2 to 5.4
On CPanel using "Select Php version" set PHP version to 7
Or on CPanel using "MultiPHP Manager" set PHP version to ea-php70
Now, cron job runs smoothly. I hope this helps someone.
|
I use cron job to do some CRUD operation using laravel Task Scheduling. On localhost and on my Share-Hosting server it worked fine for months until recently I keep getting this error when I run cron job on my Share-Hosting server. I did not make any changes to the code on my Share-Hosting server.
[2017-07-14 09:16:02] production.ERROR: exception 'Symfony\Component\Process\Exception\RuntimeException' with message 'The Process class relies on proc_open, which is not available on your PHP installation.' in /home/xxx/xx/vendor/symfony/process/Process.php:144
Stack trace:
But on localhost it works fine. Based on my finding online I have tried the following.
Contacted my hosting company to remove proc_open form disable PHP functions.
Hosting company provided custom php.ini file. I remove all disable_functions
Share-Hosting Server was restarted and cache was cleared
None of this fixed the issue. I am not sure of what next to try because the same project works fine on different Share-Hosting Server.
|
Laravel 5.2: The Process class relies on proc_open, which is not available on your PHP installation
|
The simplest way to run a cron via CodeIgniter is to make a cron URL available via your app.
Then call it via wget
wget -O - -q -t 1 http://www.example.com/cron/run
Inside the controller you can then use a log to ensure the cron is not run too often i.e. if the Google robots trigger it by mistake.
A second method would be to use lynx
/usr/local/bin/lynx -source http://www.example.com/cron/run
|
I've tried the following method in the past:
<?php
set_time_limit(0);
$_SERVER['PATH_INFO'] = 'cron/controller/index';
$_SERVER['REQUEST_URI'] = 'cron/controller/index';
require_once('index.php');
?>
and putting this in a file in the codeigniter installation directory, calling it cron.php, and then invoking it via:
php /home/[username]/public_html/my_project/cron.php
If I type the URL to cron.php in my browser it works perfectly, however whenever its run via CRON I get a 404 error. Putting the following code in the show_404() function of CodeIgniter
function show_404($page = '')
{
print_r($_SERVER);
echo "\n\n";
die ($page);
}
results in getting the following output emailed to me:
Array
(
[SHELL] => /bin/sh
[MAILTO] => [email protected]
[USER] => [me]
[PATH] => /usr/bin:/bin
[PWD] => /home/[me]
[SHLVL] => 1
[HOME] => /home/[me]
[LOGNAME] => [me]
[_] => /usr/bin/php
[PHP_SELF] =>
[REQUEST_TIME] => 1266479641
[argv] => Array
(
[0] => /home/[me]/public_html/my_project/cron.php
)
[argc] => 1
[PATH_INFO] => cron/controller/index
[REQUEST_URI] => cron/controllers/index
)
home/[me]
Here I've [me] in place of my actual username.
Any ideas?
|
How to run a CodeIgniter file through CRON?
|
17
SELinux was restricting the access to logrotate on log files in directories which does not have the required SELinux file context type. "/var/log" directory has "var_log_t" file context, and logrotate was able to do the needful. So the solution was to set this on my application log files and it's parent directory:
semanage fcontext -a -t var_log_t <directory/logfile>
restorecon -v <directory/logfile>
Share
Improve this answer
Follow
answered May 24, 2013 at 18:19
AshokAshok
53111 gold badge33 silver badges1212 bronze badges
Add a comment
|
|
I added two scripts in "logrotate.d" directory for my application logs to be rotated.
This is the config for one of them:
<myLogFilePath> {
compress
copytruncate
delaycompress
dateext
missingok
notifempty
daily
rotate 30
}
There is a "logrotate" script in "cron.daily" directory (which seems to be running daily as per cron logs):
#!/bin/sh
echo "logrotate_test" >>/tmp/logrotate_test
#/usr/sbin/logrotate /etc/logrotate.conf >/dev/null 2>&1
/usr/sbin/logrotate -v /etc/logrotate.conf &>>/root/logrotate_error
EXITVALUE=$?
if [ $EXITVALUE != 0 ]; then
/usr/bin/logger -t logrotate "ALERT exited abnormally with [$EXITVALUE]"
fi
exit 0
The first echo statement is working.
But I find my application logs alone are not getting rotated, whereas other logs like httpd are getting rotated **
**And I also don't see any output in the mentioned "logrotate_error" file (has write permission for all users).
However the syslog says: "logrotate: ALERT exited abnormally with [1]"
But when I run the same "logrotate" in "cron.daily" script manually, everything seems working fine.
Why is it not rotating during daily cron schedule? Am I doing something wrong here?
It would be great if I get this much needed help.
UPDATED:
It looks like, it's because of selinux - the log files in my user home directory has restrictions imposed by selinux and the when logrotate script is run:
SELinux is preventing /usr/sbin/logrotate from getattr access on the file /home/user/logs/application.log
|
logrotate cron job not rotating certain logs
|
You can use delayed dispatching for your queues in Laravel . https://laravel.com/docs/master/queues#delayed-dispatching
$job = (new YourEvent($coolEvent))->delay(Carbon::now()->addSeconds(90));
This will run the task 90 seconds after it's added to queue.
|
Let's say my server sends an identical request to 5 client devices at 12:00:05. I want to wait 90 seconds (until 12:01:35) and then check which clients have responded appropriately to the request and do some other stuff. What's the best way to accomplish something like this?
Should I queue up a job and use sleep(90) at the beginning? The problem is this type of job will always take at least 90 seconds to complete and the server is set by default to time out after 60 seconds. I suppose I can change the server setting, but my other jobs should still be considered to have timed out if they get past 60 seconds.
Should I queue up a scheduled task instead? The problem here is I think Laravel and cron only give you scheduling precision to the nearest minute (12:01 or 12:02, but not 12:01:35).
|
How do I time delay a job in Laravel 5.2?
|
Your redirection order is incorrect. Stderr is not being redirected to the file, but is being sent to stdout. That's what you must be receiving in your mail.
Fix the redirection by changing your cron job to:
0 5 * * * /bin/bash -l -c
'export RAILS_ENV=my_env;
cd /my_folder;
./script/my_script.rb > ./log/my_log.log 2>&1'
|
I have the following entry in crontab:
0 5 * * * /bin/bash -l -c 'export RAILS_ENV=my_env; cd /my_folder; ./script/my_script.rb 2>&1 > ./log/my_log.log'
The result of this is that I am receiving the output of ./script/my_script.rb in ./log/my_log.log. This behavior is desired. What is curious is that I am also receiving the output in my local mail. I am wondering how the output of my script is being captured by mail. Since I am redirecting the output to a log file, I would expect that my cron job would have no output, and thus I would receive no mail when the cron job runs. Can anyone shed some light as to how mail is able to get the output of ./script/my_script.rb?
|
Redirecting the output of a cron job
|
Stick with the whenever gem or similar gem e.g. chrono, clockwork, rufus-scheduler.
What you're reading in the ActiveJob documentation is a bit confusing, because it could seem as if ActiveJob may be able handle the responsibility of regular scheduling. What the documentation should say IMHO is that the jobs are regularly scheduled by some other system or tool.
So, ActiveJob is about queued jobs?
Yes, it's about Rails providing a standard interface for adding a job to a queue, and calling a perform method. ActiveJob provides the method interfaces that enable adapters for many job-processing queues, backends, immediate runners, etc.
|
I'm aware of this thread: A cron job for rails: best practices?, but there's no mention of ActiveJob. My motivation to do it with ActiveJob is because it's built-in in Rails and here's an excerpt from its docs:
"These jobs can be everything from regularly scheduled clean-ups, to billing charges, to mailings."
How do I create a daily job (cron-like) in Rails ActiveJob? Since I don't see the example to run a regularly scheduled job in its docs.
Or should I stick with the whenever gem?
|
How to create a daily job (cron-like) in Rails ActiveJob?
|
21
I've got (something very much like) this in a ./roles/cron/tasks/main.yml file:
- name: Creates weekly backup cronjob
cron: minute="20" hour="5" weekday="sun"
name="Backup mysql tables (weekly schedule)"
cron_file="mysqlbackup-WeeklyBackups"
user="root"
job="/usr/local/bin/mysqlbackup.WeeklyBackups.sh"
tags:
- mysql
- cronjobs
The shell script listed in the 'job' was created a little earlier in the main.yml file.
This task will create a file in /etc/cron.d/mysqlbackup-WeeklyBackups:
#Ansible: Backup mysql tables (weekly schedule)
20 5 * * sun root /usr/local/bin/mysqlbackup.WeeklyBackups.sh
Share
Improve this answer
Follow
edited Jan 20, 2015 at 9:50
answered Jan 19, 2015 at 20:36
Alister BulmanAlister Bulman
34.8k99 gold badges7272 silver badges111111 bronze badges
2
Does this just creates the file or also sets it up to execute it? I tried doing the same in my playbook. The file got created in the place mentioned. But when I am executing crontab -l I get the message no crontab for user
– Ishan
Jun 12, 2016 at 19:59
4
crontabs -l only looks in '/var/spool/cron/crontabs/{username}'.
– Alister Bulman
Jun 13, 2016 at 6:34
Add a comment
|
|
I want to setup cronjobs on various servers at the same time for Data Mining. I was also already following the steps in Ansible and crontabs but so far nothing worked.
Whatever i do, i get the Error Message:
ERROR: cron is not a legal parameter at this level in an Ansible Playbook
I have: Ansible 1.8.1
And for some unknown reasons, my Modules are located in:
/usr/lib/python2.6/site-packages/ansible/modules/
I would like to know which precise steps i have to follow to let Ansible install a new cronjob in the crontab file.
How precisely must a playbook look like to install a cronjob?
What is the command line to start this playbook?
I'm asking this odd question because the documentation of cron is insufficient and the examples are not working. Maybe my installation is wrong too, which I want to test out with a working example of cron.
|
ansible creating working cronjobs
|
It sounds you are storing your schedule of tasks in the database. No problem. For every different type of task (eg. sending newsletter, save reports) create a service, which does the task. Then add to this services a tag (like twig.extension, but your own), so you have something like a TaskChain, which knows all the tasks.
For executing create a console command, which retrieves the schedule from the database, loads the TaskChain, and executes the tasks. This console command can be simply called from a cronjob without exposing it to the web. In fact your are calling this command via the php-cli and not from a browser, the standard time limit is unlimited. No controllers should be involved for executing.
This should be all organized in an extra TaskBundle.
|
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Needs more focus Update the question so it focuses on one problem only by editing this post.
Improve this question
My application based on symfony2 has to do some standalone jobs at differents moments and differents frequencies. For exemple, sending newsletter, editing report ...
I want to be able to add/edit each task from the application
My task would be very close to cron jobs and will consist to call a specific url.
From my point of view :
I think about creating a cron job that launch a script every half hour, or ten minutes. this script only do a curl command witch get a docronjob action. This docronjobaction is inside symfony and is responsible to get all the task and launch the one it has to.
My questions are :
Is there a cleaner way to achive that ?
Inside the docronaction how do I launch others action ?
How do I manage to set the time limit to 0 for an entire controller ?
Does a bundle doing this allready exist ?
|
best practice how to schedule symfony2 action [closed]
|
If your ruby is in non standard paths then personally I like to wrap my ruby calls in a shell script, thereby ensuring that all the paths etc. my ruby program needs are set correctly, and schedule the script in crontab. Do something like
2 * * * * /home/mark/project/ruby_wrapper_sh >> /home/mark/cronOutput.txt 2>&1
and your /home/mark/project/ruby_wrapper_sh should read something like
#!/bin/bash
. ~mark/.bash_profile
`ruby /home/mark/project/script.rb`
|
I want to create a cron job to run a ruby script. this is what i have put in the crontab.
2 * * * * ruby /home/mark/project/script.rb >> /home/mark/cronOutput.txt
But its not running. I think there's some problem with the environment getting loaded up when the cron runs as root.
Please help.
|
how to create a cron job to run a ruby script?
|
To answer my own question, just 8 hours later: It IS possible to issue cron jobs on Amazon Lightsail instances
Here is a working example of running a PHP script:
Connect to your Lightsail instance either by logging in to your lightsail account and clicking "Connect using SSH" or using a SSH client, such as PuTTY.
Create a folder called 'projects' in /home/bitnami/ and create a simple .php file called Hello World:
<?php print("Hello World"); ?>
Use command crontab -e to access a document, from where you can add lines that will be your scheduled cron jobs.
Append two lines to the document AND ADD A NEWLINE:
PATH=/usr/bin:/bin:/opt/bitnami/php/bin:
* * * * * php -f /home/bitnami/projects/HelloWorld.php > /home/bitnami/projects/Out.put
Line 1 adds php to the cron path (Cron sees a different path than what is given in the environment variables. Type: env and hit enter in the console). To see which env variables are given to cron replace line 2 with: * * * * * env > /tmp/env.output and look in the file. Line 2 is the cron schedule. The asterisks means: Do this every minute of every hour, day, month, year. Search Google for this :) And will output to a file called Out.put.
Wait 1 minute and see that Out.put has been created and contains the magic words of Hello World
If you are having problems with cron jobs not working, check out this troubleshooting guide: https://stackoverflow.com/tags/cron/info
Hope this helps. If it does not, post a comment before downvoting!
|
I would like to set up periodic jobs on an Amazon Lightsail instance, but I can find no information on it - only for Amazon EC2.
Is it possible to issue cron jobs on a lightsail instance, or do I need to change to EC2?
|
Is it possible to have cron job running on Amazon lightsail instance?
|
simple:
get the data locally and use mellissa data:
for ip: http://w10.melissadata.com/dqt/websmart/ip-locator.htm
for phone: http://www.melissadata.com/fonedata.html
you can also cache them using memcache or APC which will make it faster since he does not have to request the data from the api or database.
|
I have a cronjob that runs every hours and parse 150,000+ records. Each record is summarized individually in a MySQL tables. I use two web services to retrieve the user information.
User demographic (ip, country, city etc.)
Phone information (if landline or cell phone and if cell phone what is the carrier)
Every time I get 1 record I check if I have information and if not I call these web services. After tracing my code I found out both of these calls takes 2 to 4 seconds and it makes my cronjob very slow and I can't compile statistics on time.
Is there a way to make these web service faster?
Thanks
|
Cronjob: Web Service query
|
I think should be able to define a trigger that can repeat every hour until a certain time:
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;
...
Trigger myTrigger = newTrigger()
.withIdentity('myUniqueTriggerID")
.forJob(myJob)
.startAt(startDate)
.endAt(endDate)
.withSchedule(simpleSchedule().withIntervalInHours(1));
...
scheduler.scheduleJob(myJob, myTrigger);
|
I know every five minutes is:
0 0/5 * * * *
But how do I limit the number hours for this to happen?
Example: Every five minutes for the next 10 hours.
|
Cron expression for every five minutes in the next n hours?
|
9
Try following which you will get closest in one expression
0 0 10,15/12 * * ?
this will run 10:00 and 15:00.
Share
Improve this answer
Follow
edited Jan 26, 2017 at 15:25
fedorqui
281k105105 gold badges565565 silver badges607607 bronze badges
answered Jan 26, 2017 at 14:56
jjjjjj
1,14433 gold badges1818 silver badges2828 bronze badges
7
3
Why the /12 ?
– fedorqui
Jan 26, 2017 at 15:25
/12 - means it run every 12 hours which make twise a day.
– jjj
Jan 26, 2017 at 17:05
It does if you just say /12, but your current 10,15/12 says at minute 0 past hour 10 and every 12th hour from 15 through 23. crontab.guru/#0_10,15/12___*
– fedorqui
Jan 27, 2017 at 7:49
nope - /12 means 2 times a day not 1 time in 24 hours at different time specified 10 and 15. you can test this one at cronmaker.com
– jjj
Jan 27, 2017 at 7:55
2
yes I know what /12 does, my point is that 15/12 does not make any sense.
– fedorqui
Jan 27, 2017 at 9:20
|
Show 2 more comments
|
I have one job that needs to be execute twice a day at different time .
e.g. 10:00 and 15:30.
How can i achieve this ?
I am confuse because minute is different for both the time.
For 11:00 and 15:00 its easy because for both the times, minute portion is same, but for the different minute portion is it feasible with cron ?
Thanks in Advance and apologies for silly question.
|
Cron expression to run job twice a day at different time?
|
You should use enviroment variables.
In your code you will check this env var:
if(process.env.WITH_SCHEDULE) {
...
}
When you start your instances, you will set WITH_SCHEDULE only for one instance.
Example pm2.json:
{
"apps": [
{
"name": "Example",
"script": "boot/app/app.js",
"args": [],
"error_file": "/srv/www.example.com/logs/error.log",
"out_file": "/srv/www.example.com/logs/info.log",
"ignore_watch": [
"node_modules"
],
"watch": false,
"cwd": "/srv/www.example.com/server",
"env": {
"NODE_ENV": "production",
"WITH_SCHEDULE": "1",
"HOST": "127.0.0.1",
"PORT": "9030"
}
},
{
"name": "Example",
"script": "boot/app/app.js",
"args": [],
"error_file": "/srv/www.example.com/logs/error.log",
"out_file": "/srv/www.example.com/logs/info.log",
"ignore_watch": [
"node_modules"
],
"watch": false,
"cwd": "/srv/www.example.com/server",
"env": {
"NODE_ENV": "production",
"HOST": "127.0.0.1",
"PORT": "9030"
}
}
]
}
|
My question is how to use node-schedule to run a cron only on one instance out of two instances of node server.
Currently it is running on both instances but I want it to be executed only on one instance.
So How can you make a cluster run a task only once?
Thanks in advance.
{
"apps": [
{
"name": "Example",
"script": "boot/app/app.js",
"watch": false,
"exec_mode": "cluster_mode",
"instances": 2,
"merge_logs": true,
"cwd": "/srv/www.example.com/server",
"env": {
"NODE_ENV": "development",
.......
.......
}
}
]
}
|
how to use node-schedule to run a cron only on one instance?
|
I got it solved with the help of How to run a cron job inside a docker container? however, I had to add the line:
RUN crontab /etc/cron.d/crontab
which basically Loads the crontab data from the specified file. If i did not do it that way, the cron daemon never starts.
Hope this helps however, still not clear if this is the best way to do this.
|
here is the thing: I have a stack where a node js backend sends messages to a queue and perl workers (cron jobs) consume messages from that queue. I already "dockerized" the node js backend but now I'm trying to do the same with the Perl Workers.
Already dockerized the Perl application itself however, as the "jobs" from the queue are consumed based on a crontab (i.e every 2 mins) my question would be:
What's the best way to accomplish this when having a stack built from a docker-compose file?
Let me know if I should provide more details. Thanks!
|
Best practices to run cron job from a docker stack
|
The second Saturday of the month falls on one (and only one) of the dates from the 8th to the 14th inclusive. Likewise, the fourth Saturday falls on one date between the 22nd and the 28th inclusive.
You may think that you could use the day of week field to limit it to Saturdays (the 6 in the line below):
0 1 8-14,22-28 * 6 /path/to/myscript
Unfortunately, the day-of-month and day-of-week is an OR proposition where either will cause the job to run, as per the manpage:
Commands are executed by cron when the minute, hour, and month of year fields match the current time, and when at least one of the two day fields (day of month, or day of week) match the current time.
The day of a command's execution can be specified by two fields - day of month, and day of week. If both fields are restricted (i.e., aren't *), the command will be run when either field matches the current time. For example, 30 4 1,15 * 5 would cause a command to be run at 4:30 am on the 1st and 15th of each month, plus every Friday.
Hence you need to set up your cron job to run on every one of those days and immediately exit if it's not Saturday.
The cron entry is thus:
0 1 8-14,22-28 * * /path/to/myscript
(to run at 1am on each possible day).
Then, at the top of /path/to/myscript, put:
# Exit unless Saturday
if [[ $(date +%u) -ne 6 ]] ; then
exit
fi
And, if you can't modify the script (e.g., if it's a program), simply write a script containing only that check and a call to that program, and run that from cron instead.
You can also put the test for Saturday into the 0 1 8-14,22-28 * 6 /path/to/myscript
0 file itself to keep the scheduling data all in one place:
0 1 8-14,22-28 * 6 /path/to/myscript
1
|
What's the cron (linux) syntax to have a job run on the 2nd and 4th Saturday of the month?
|
Run every 2nd and 4th Saturday of the month
|
41
I use Laravel 5.2 and the kernel calls my drivers this way:
$schedule->call('App\Http\Controllers\MyController@MyAction')->everyMinute();
Share
Improve this answer
Follow
edited Oct 31, 2023 at 21:48
TylerH
21k7070 gold badges7878 silver badges104104 bronze badges
answered May 17, 2016 at 14:11
Jennifer Miranda BeusesJennifer Miranda Beuses
73777 silver badges1515 bronze badges
2
@BinitGhetiya How did you add parameter option?
– Salman Riyaz
Mar 27, 2020 at 7:15
although this answer solve the OP problem but i really think that the cron should call a service function not a controller one, i would put the logic you have in that controller function inside a service and i will call it from the controller and the cron
– George
Jun 6, 2020 at 9:15
Add a comment
|
|
I work with Laravel Task Scheduling, but I have a problem when I call some method from my controller.
protected function schedule(Schedule $schedule)
{
$schedule->call('UserController@deleteInactiveUsers')->everyMinute();
//$schedule->call('App\Http\Controllers\UserController@deleteInactiveUsers')->everyMinute();
}
When I call with uncommented line i get this error:
[ReflectionException]
Class RecurrenceInvoiceController does not exist
and then I insert fully qualified namespace path and then I get this error:
[PDOException] SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known
And
[ErrorException] PDO::__construct(): php_network_getaddresses: getaddrinfo failed: Name or service not known
Where is the problem? Which way is correct to call method from Controller from Laravel Task Scheduling.
|
Laravel Scheduling call controller
|
For starters, I'd recommend using the command line version of PHP rather than using curl to call a script. You can then create a PHP script with a sensible lifetime that isn't constrained by having to output a response within a given time period.
As such, you can then simply sleep/check for emails/transmit/sleep, etc. within the PHP script rather than needlessly using cron.
Additionally, I'd take care to ensure that multiple PHP scripts aren't operating on the database table at the same time, either by using a pid file or database setting approach (if a given file/setting exists/is set, abort processing) or by sensibly timing the cron job and limiting the maximum processing time of the script by checking how long it's been running for prior to beginning the "check for emails" portion of the cycle.
|
I created a Email-Queue database table. I will insert all Emails my PHP application needs to send into this table.
Another PHP script will then look for all unsent Emails and sends them.
I run this script using cronjobs. Unfortunately cronjobs can run only at a maximum of once per minute.
So in the worst-case a user has to wait one minute until his Email is really going to be sent.
My current idea for a workaround is calling the script with an addtional sleep parameter and duplicating the cronjobs.
Example:
* * * * * curl emails.php?sleep=0 >/dev/null 2>&1
* * * * * curl emails.php?sleep=10 >/dev/null 2>&1
* * * * * curl emails.php?sleep=20 >/dev/null 2>&1
* * * * * curl emails.php?sleep=30 >/dev/null 2>&1
* * * * * curl emails.php?sleep=40 >/dev/null 2>&1
* * * * * curl emails.php?sleep=50 >/dev/null 2>&1
In the above example the script would run every 10 seconds. The first line of the emails.php Script would be:
sleep($_REQUEST['sleep']);
|
How to run Cronjobs more often than once per minute?
|
To delete the auto-generated cronjobs from your crontab, run whenever against your defintion file with the -c flag:
$ whenever -c theCronJob
Alternatively, open your crontab...
$ crontab -e
... and then manually delete the undesired entries.
|
I'm using the "whenever" gem and got it working by doing:
whenever --set environment=production --update-crontab theCronJob
The interval I'm using is 2 minutes since I'm still trying to figure it out. However, now I get a You have mail message in my terminal window every 2 minutes. I guess the cron runs and lets me know about it. How do I stop my cron from running? These messages are starting to pile up.
Thank you
|
How to stop cron jobs created by "whenever" gem
|
From man 5 crontab
field allowed values
----- --------------
minute 0-59
hour 0-23
day of month 1-31
month 1-12 (or names, see below)
day of week 0-7 (0 or 7 is Sun, or use names)
Or, in other words
# m h dom mon dow user command
15,45 * * * * yourusername wget -O /dev/null http://somesite.com/4_leads.php
Skip the username field if you place the entry in a user specific crontab, via crontab -e, crontab -e -u yourusername, or similar.
This question may be better suited to serverfault.
|
What is the syntax for a cron job that runs 15 and 45 minutes after the hour? (So every 30 minutes.)
Would the syntax be something like:
15,45,30 * * * * wget -O /dev/null http://somesite.com/4_leads.php
So for example it would run at
2:15
2:45
3:15
3:45
4:15
4:45
and so on
|
What is the syntax for a cron job that runs 15 and 45 minutes after the hour?
|
You can do it using the following command:
wget <URL> -O ->> <FILE_NAME>
|
I am running wget through cronjob for executing some script in scheduled manner. Everytime the output is downloaded and saved as new file. I want to append the output to same file. How can I do that?
I am talking about the downloaded content from the URL but not the log of the execution.
|
How to append the wget downloaded file?
|
Use the PHP cURL extension. Unlike fopen() it can also make HTTP HEAD requests which are sufficient to check the availability of a URL and save you a ton of bandwith as you don't have to download the entire body of the page to check.
As a starting point you could use some function like this:
function is_available($url, $timeout = 30) {
$ch = curl_init(); // get cURL handle
// set cURL options
$opts = array(CURLOPT_RETURNTRANSFER => true, // do not output to browser
CURLOPT_URL => $url, // set URL
CURLOPT_NOBODY => true, // do a HEAD request only
CURLOPT_TIMEOUT => $timeout); // set timeout
curl_setopt_array($ch, $opts);
curl_exec($ch); // do it!
$retval = curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200; // check if HTTP OK
curl_close($ch); // close handle
return $retval;
}
However, there's a ton of possible optimizations: You might want to re-use the cURL instance and, if checking more than one URL per host, even re-use the connection.
Oh, and this code does check strictly for HTTP response code 200. It does not follow redirects (302) -- but there also is a cURL-option for that.
|
Given a list of urls, I would like to check that each url:
Returns a 200 OK status code
Returns a response within X amount of time
The end goal is a system that is capable of flagging urls as potentially broken so that an administrator can review them.
The script will be written in PHP and will most likely run on a daily basis via cron.
The script will be processing approximately 1000 urls at a go.
Question has two parts:
Are there any bigtime gotchas with an operation like this, what issues have you run into?
What is the best method for checking the status of a url in PHP considering both accuracy and performance?
|
How do I check for valid (not dead) links programmatically using PHP?
|
Instead of a random value, you could get something related to the node, like an hash of the hostname or the last byte of the ip address.
This is an example:
- name: Get a pseudo-random minute
shell: expr $((16#`echo "{{inventory_hostname}}" | md5sum | cut -c 1-4`)) % 30
register: minute
changed_when: false
|
Is there a way to guarantee idempotence for playbooks that use randomly generated variables?
For example, I want to setup my crontabs to trigger emails on multiple servers at different times, so I create random integers using ansible's set_fact module:
tasks:
- set_fact:
first_run_30="{{ 30 | random }}"
run_once: yes
Then apply those generated variables to my crontab using ansible like so:
- name: Setup cron30job
cron: name=cron30job minute={{first_run_30}},{{first_run_30 | int + 30}} job='/bin/bash /cron30job.sh' state=present user=root
environment:
MAILTO: '[email protected]'
MAILFROM: '[email protected]'
This works very well, however, ansible's indempotence principle is, I believe, broken using this strategy because each time a play is made you see a change:
TASK: [Setup cron30job] *****************************************
changed: [127.0.0.1]
Further, in the crontab checking under root each time during three separate runs:
[ansible]# cat /var/spool/cron/root
#Ansible: cron30job
5,35 * * * * /bin/bash /sw/test/cron30job.sh
#Ansible: cron30job
9,39 * * * * /bin/bash /sw/test/cron30job.sh
#Ansible: cron30job
6,36 * * * * /bin/bash /sw/test/cron30job.sh
If there is a workaround, or maybe indempotence just will not be possible in my scenario, I would like to know.
|
Idempotence and Random Variables in Ansible
|
Amazon has just released[1] new features for Elastic Beanstalk. You can now create a worker environment containing cron.yaml that configures scheduling tasks calling an URL with the CRON syntax: http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/using-features-managing-env-tiers.html#worker-periodictasks
[1] http://aws.amazon.com/about-aws/whats-new/2015/02/17/aws-elastic-beanstalk-supports-environment-cloning-periodic-tasks-and-1-click-iam-role-creation/
|
I have a website running on AWS EC2. I need to create a nightly job that generates a sitemap file and uploads the files to the various browsers. I'm looking for a utility on AWS that allows this functionality. I've considered the following:
1) Generate a request to the web server that triggers it to do this task
I don't like this approach because it ties up a server thread and uses cpu cycles on the host
2) Create a cron job on the machine the web server is running on to execute this task
Again, I don't like this approach because it takes cpu cycles away from the web server
3) Create another EC2 instance and set up a cron job to run the task
This solves the web server resource issues, but why pay for an additional EC2 instance to run a job for <5 minutes? Waste of money!
Are there any other options? Is this a job for ElasticMapReduce?
|
Scheduling A Job on AWS EC2
|
Because they haven't been the subject of a wait(2) system call.
Since someone may wait for these processes in the future, the kernel can't completely get rid of them or it won't be able to execute the wait system call because it won't have the exit status or evidence of its existence any more.
When you start one from the shell, your shell is trapping SIGCHLD and doing various wait operations anyway, so nothing stays defunct for long.
But cron isn't in a wait state, it is sleeping, so the defunct child may stick around for a while until cron wakes up.
Update: Responding to comment...
Hmm. I did manage to duplicate the issue:
PPID PID PGID SESS COMMAND
1 3562 3562 3562 cron
3562 1629 3562 3562 \_ cron
1629 1636 1636 1636 \_ sh <defunct>
1 1639 1636 1636 sleep
So, what happened was, I think:
cron forks and cron child starts shell
shell (1636) starts sid and pgid 1636 and starts sleep
shell exits, SIGCHLD sent to cron 3562
signal is ignored or mishandled
shell turns zombie. Note that sleep is reparented to init, so when the sleep exits init will get the signal and clean up. I'm still trying to figure out when the zombie gets reaped. Probably with no active children cron 1629 figures out it can exit, at that point the zombie will be reparented to init and get reaped. So now we wonder about the missing SIGCHLD that cron should have processed.It isn't necessarily vixie cron's fault. As you can see here, libdaemon installs a SIGCHLD handler during daemon_fork(), and this could interfere with signal delivery on a quick exit by intermediate 1629Now, I don't even know if vixie cron on my Ubuntu system is even built with libdaemon, but at least I have a new theory. :-)
|
I have some processes showing up as <defunct> in top (and ps). I've boiled things down from the real scripts and programs.
In my crontab:
* * * * * /tmp/launcher.sh /tmp/tester.sh
The contents of launcher.sh (which is of course marked executable):
#!/bin/bash
# the real script does a little argument processing here
"$@"
The contents of tester.sh (which is of course marked executable):
#!/bin/bash
sleep 27 & # the real script launches a compiled C program in the background
ps shows the following:
top0
Note that top1 does not appear--it has exited after launching the background job.
Why does top2 stick around, marked top3? It only seems to do this when launched by top4--not when I run it myself.
Additional note: top5 is a common script in the system this runs on, which is not easily modified. The other things (top6, top7, even the program that I run instead of top8) can be modiified much more easily.
|
Why do processes spawned by cron end up defunct?
|
14
you can use
10 3 * * 0 /usr/local/bin/docker-compose -f /www/ilanni.com/docker-compose.yml start > /dev/null
Share
Improve this answer
Follow
edited Aug 4, 2020 at 17:56
Daniel W.
31.7k1313 gold badges9595 silver badges152152 bronze badges
answered Aug 25, 2018 at 3:38
lanni654321lanni654321
1,0591111 silver badges77 bronze badges
Add a comment
|
|
I recently have a problem when I want to execute docker-compose command in crontab.
I have a docker-compose YAML file that defined all the services I need, say “docker-compose.yml". And I also have a Makefile in which I had written some command to do something.
My makefile is:
.PHONY operate
operate:
/usr/local/bin/docker-compose -p /project -f ~/docker-compose-production.yml run rails env
This make script worked fine when it executed in shell. It listed all the environment var I defined in docker-compose.yml. But when I putted it in crontab.
The result became strange, it listed nothing but only the $PATH.
My crontab file is:
57 21 * * * make -f ~/Makefile operate >~/temp 2>&1
I guess there must be some environment var that docker-compose must have but I don’t know. Do you have any idea about this problem?
|
docker-compose with crontab
|
SERVERNUM=$1
To enable:
crontab -l | sed "/^#.*Server $SERVERNUM check/s/^#//" | crontab -
To disable:
crontab -l | sed "/^[^#].*Server $SERVERNUM check/s/^/#/" | crontab -
Transcript:
barmar@dev$ crontab -l
*/1 * * * * Server 1 check
*/1 * * * * Server 2 check
*/1 * * * * Server 3 check
barmar@dev$ crontab -l | sed '/^[^#].*Server 1 check/s/^/#/' | crontab -
barmar@dev$ crontab -l
#*/1 * * * * Server 1 check
*/1 * * * * Server 2 check
*/1 * * * * Server 3 check
barmar@dev$ crontab -l | sed '/^#.*Server 1 check/s/^#//' | crontab -
barmar@dev$ crontab -l
*/1 * * * * Server 1 check
*/1 * * * * Server 2 check
*/1 * * * * Server 3 check
|
Is there a way to enable and disable Crontab tasks using Bash/Shell?
So when the user starts Server 1, it will enable the Server 1 Crontab line and so on.
And when the user stops Server 1, the Server 1 Crontab line get disabled (#).
Is this possible and how?
Thanks in advance
*/1 * * * * Server 1 check
*/1 * * * * Server 2 check
*/1 * * * * Server 3 check
|
Enable/Disable tasks in Crontab by Bash/Shell
|
Just change your trigger to
0 0 3 L * ?
One of day of week or day of month needs to be ?. You cannot specify both.
|
I need to run a job on the last day of every month. i tried the following cron expression:
<property name="cronExpression" value="0 0 3 L * * *" />
but got this error:
Caused by: java.lang.UnsupportedOperationException: Support for specifying both a day-of-week AND a day-of-month parameter is not implemented.
it doesnt like the L, but without using it, how can i run on the last day of the month?
|
quartz scheduler: run on last day of the month
|
Although kubectl currently does not allow you to use the --from flag and specify a command in the same clause, you can work around this limitation by getting the yaml from a dry run and using yq to apply a patch to it.
For example:
# get the original yaml file
kubectl create job myjob --from cronjob/mycronjob --dry-run=client --output yaml > original.yaml
# generate a patch with your new arguments
yq new 'spec.template.spec.containers[0].args[+]' '{INSERT NEW ARGS HERE}' > patch.yaml
# apply the patch
yq merge --arrays update patch.yaml original.yaml > final.yaml
# create job from the final yaml
kubectl create -f final.yaml
|
Kubectl allows you to create ad hoc jobs based on existing crons.
This works great but in the documentation there is no specification for passing arguments upon creation of the job.
Example:
kubectl -n my-namespace create job --from=cronjob/myjob my-job-clone
Is there any way I can pass arguements to this job upon creation?
|
Kubectl create job from cronjob and override args
|
Why are you using nohup? nohup is a command that tells the running terminal to ignore the hangup signal. cron, however, has no hangup signal, because it is not linked to a terminal session.
In this case, instead of:
nohup scrapy crawl first &
You probably want:
scrapy crawl first > first.txt &
The last example also works in a terminal, but when you close the terminal, the hangup signal (hup) is sent, which ends the program.
|
i have start.sh bash script that is running though CRON JOB on ubuntu server
start.sh contains bellow mentioned lines of code
path of start.sh is /home/ubuntu/folder1/folder2/start.sh
#!/bin/bash
crawlers(){
nohup scrapy crawl first &
nohup scrapy crawl 2nd &
wait $!
nohup scrapy crawl 3rd &
nohup scrapy crawl 4th &
wait
}
cd /home/ubuntu/folder1/folder2/
PATH=$PATH:/usr/local/bin
export PATH
python init.py &
wait $!
crawlers
python final.py
my issue is if i run start.sh my myself on command line it outputs in nohup.out file
but when it executes this bash file through cronjob (although scripts are running fine) its not producing nohup.out
how can i get output of this cronjob in nohup.out ?
|
cron job doesn't output to nohup.out
|
This is your cron job:
*/2 * * * *
But then you state:
How to skip the "0" minute of the "0" hour (12AM) in the cron? I do
this because this cron depends on another cron which runs once daily
at 12AM. So I don't want them to overlap.
The problem is not the cron job but rather your script logic. Perhaps you could do something like create some kind of indicator in the first job that the second job would pick up on so they don’t conflict.
Perhaps you should just change your cron to be the inelegant, but specific of every 2 minutes like this:
2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58 * * * *
One concept would be to combine an interval (2-58) with a frequency (*/2), but unclear if this could work.
2-58/2 * * * *
EDIT: According to the comment left by the original poster:
In short, I need this cron to run every 2 minutes except 12AM.
If that is the case, you might have to set a mix of cron jobs like this:
*/2 1-23 * * *
2-58/2 0 * * *
The first cron entry would run the job every 2 minutes from 1:00am to 11:00pm.
The next cron entry would run the job every 2 minutes from 2-58 minutes only at midnight. Since this second job skips 0 during the 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58 * * * *
0 hour of midnight this combo should work for you.
But that said, this kind of dual entry logic is why it’s actually encouraged that developers expand their app logic to avoid certain scenarios it won’t work.
For example, I have some bash scripts that create lock files in the standard Unix 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58 * * * *
1 directory. They are set to run every 5 minutes, but the script itself has logic to make sure the first thing it does before anything is to check if that lock is present. If the lock is there? Do nothing. If the lock is not there, go nuts!
|
I have a simple cron job inside cPanel that runs every 2 minutes:
*/2 * * * *
By default the "0" minute is the start of the cron job like 0,2,4,6,8,10 etc...
How to skip the "0" minute of the "0" hour (12AM) in the cron? I do this because this cron depends on another cron which runs once daily at 12AM. So I don't want them to overlap.
In short, I need this cron to run every 2 minutes except 00:00 at 12:00AM.
|
Run cron job every 2 minutes except the first minute "0" of the first hour "0"
|
This was the answer:
Use /usr/local/bin/php instead of /usr/bin/php to get codeigniter to pick up on the URI segments.
|
SOLVED:
Crap... why is it always you figure something out right AFTER you finally decided to ask for help!!
If anyone else is having this problem, try running from /usr/local/bin/php instead of /usr/bin/php to get codeigniter to pick up on the URI segments.
QUESTION
I have the latest installation of codeigniter and everything seems to be working fine locally. I recently put my files on my server and everything except my cron command is working.
When I try to call a controller through cron (as described here: http://codeigniter.com/user_guide/general/cli.html), I am not getting the controller. Instead, the output I get is simply my default controller (login page).
This worked fine locally and the index.php IS getting called because I'm getting emailed the output from the default page.
Someone asked a similar question here: CodeIgniter Cron Job on Shared Hosting? Responders suggested that it was a problem with Cpanel (which is what i'm now trying to use to set up the cron job), but talking to my hosting provider, they said the whole command is being run. Nevertheless, CI isn't grabbing the URI for the controller. I also checked to make sure the base_url is set correctly (which is proven by the file working fine through a URL call).
Any thoughts? I just can't seem to figure out why it's not grabbing the URI when in command line format: /usr/bin/php index.php controller_class method
|
CodeIgniter + Command Line + Cron + Cpanel
|
You can use an online cron service to essentially pretend like you have cron access.
Create php file with contents you would like executed
Free Cron Online Website
Set up your free online cron to execute that file every x minutes.
|
I'd probably figure out a way to do this if I had full access to the server, however the problem is it's just a hosting service which leaves me with nothing but FTP access.
I would like to run a PHP script periodically to check for outdated/broken content, aggregate new content, delete files not in use etc, however the script can take up to 60 seconds to execute (due to aggregation of content) and I feel like an ass to just execute it while processing a request of the first user that visits the website an hour after it's been updated :P
Leaving my home PC on 24/7 to schedule requests is not an option.
|
Best way to periodically execute a PHP script?
|
18
The script can be run daily and wrapped to check if the number of days modulo 45 equals to a constant:
10 13 * * * test $(( `date +\%s`/24/60/60\%45 )) = 41 && your_script
I assumed 41 so the expression would evaluate to true today on 2012-01-12. Percent '%' is special character in crontab, it needs to be escaped.
Share
Improve this answer
Follow
edited Mar 15, 2018 at 21:47
answered Jan 2, 2012 at 9:18
kubanczykkubanczyk
5,40311 gold badge4545 silver badges5555 bronze badges
3
2
I can't figure out what the 41 relates to. Could someone help explain?
– GustavMahler
Mar 15, 2018 at 21:26
3
I wanted that condition to be true on 2012-01-12 when OP would presumably test this answer. So I calculated that I need to pick "day number 41 of each 45 day period" as a run day.
– kubanczyk
Mar 15, 2018 at 21:44
Ah I see. Thanks
– GustavMahler
Mar 15, 2018 at 21:55
Add a comment
|
|
I want to send an email after every 45 days using cron job. Since, i have already made php
script for email. So i want to execute it after every 45 days. Can you help me for this?
|
How to set cron job for every 45 days
|
The answer is yes, and the output is mailed to the account that is running the cron task. You can change this in the crontab file by setting a "MAILTO=accountname" option, like this example cron file:
MAILTO=root
# run a script every hour
01 * * * * root run-parts /etc/cron.hourly
#etc.
Any output from the above cron task would be mailed to the root user. As Mike B posted, you can also simply redirect the output elsewhere on the task line using the > operator:
01 * * * * php testscript.php > /var/log/logfile.log
in which case cron does not see it and does not send an email.
The bottom line is that if you leave some echo statements in a PHP script and set it as a cron job, then you will start getting emails from the cron daemon.
|
So I have a script that I debug with a bunch of echo statements. This is run every 3 minutes on my server by cron, and I sometimes leave the echo statements in there. They're not going to a browser, they're just going... anywhere?
This is a vague question I guess, but what happens when there's no end-user or output for an echo statement? Does it hog up memory? Does it just vanish? I'd appreciate any help in understanding this.
|
If I echo a statement and no one hears it, does it ever get echoed? (PHP cron job question)
|
13
With macos Monterey it seems you should use the following shell command
log show --process cron
you can add --info and/or --debug if required
Share
Improve this answer
Follow
answered Jan 7, 2022 at 3:18
VaughanRVaughanR
32722 silver badges88 bronze badges
4
I get the folloring error. Any suggestion? log: unrecognized option '--process'
– Fed
Jun 19, 2022 at 22:01
See man log: ... log show [--archive archive | --file file] [--predicate filter] [--process pid | process] [--source] [--style default | compact | json | ndjson | syslog] [--color auto | always | none] [--start date/time] [--end date/time] [--[no-]info] [--[no-]debug] [--[no-]pager] [--[no-]signpost] [--last time [m|h|d]] [--timezone local | timezone] ...
– VaughanR
Jun 20, 2022 at 23:12
I checked the man page and it doesn't show the process flag for the show command unfortunately. Hence why I asked for suggestions. log show [--archive archive | --file file] [--predicate filter] [--source] [--style default | compact | json | syslog] [--color auto | always | none] [--start date/time] [--end date/time] [--[no-]info] [--[no-]debug] [--[no-]signpost] [--last time [m|h|d]] [--timezone local | timezone]
– Fed
Jun 21, 2022 at 11:31
It seems not working on my device which is running macOS Ventura 13.4.
– xinbenlv
Sep 10, 2023 at 20:53
Add a comment
|
|
What is the best way to determine if a cron job has run? Is there a log? What techniques do people use?
|
Mac OS X cron log / tracking
|
A cronjob is just a single entry in a crontab, that's all.
|
This question may sound incredibly stupid, but if I don't ask I'll never know...
All the tasks setting I do is always by using "crontab". I heard the term "cronjob" somewhere. Is it another tool or just a name for something in "crontab"?
|
What's the difference between crontab and cronjob?
|
It's not a bad method, but you need to ensure that by closing the socket it isn't just terminating the script before it finishes. You can set sockets to non-blocking.
I would still use a cron job, even if it is a bit of a pain.
|
I know there are many posts about using CRON to run a php file. But, in the world of shared hosting, and ease of setup for a user, I don't want to have to mess with that.
I found another solution online that has to do with sockets. Just wanted to get everyones take on this, and tell me if this is a good or bad idea. Sounds like it works well.
Thoughts?
//Open socket connection to cron.php
$socketcon = fsockopen($_SERVER['HTTP_HOST'],80,$errorno,$errorstr,10);
if($socketcon) {
$socketdata = "GET /cron.php HTTP 1.1\r\nHost: ".$_SERVER['HTTP_HOST']."\r\nConnection: Close\r\n\r\n";
fwrite($socketcon,$socketdata);
//Normally you would get all the data back with fgets and wait until $socketcon reaches feof.
//In this case, we just do this:
fclose($socketcon);
} else {
//something went wrong. Put your error handler here.
}
cron.php:
//This script does all the work.
sleep(200);
//To prove that this works we will create an empty file here, after the sleep is done.
//Make sure that the webserver can write in the directory you're testing this file in.
$handle = fopen('test.txt','w');
fclose($handle);
Found the script from a blog post: http://syn.ac/tech/13/creating-php-cronjobs-without-cron-and-php-cli/
|
Schedule scripts without using CRON
|
You can use this small library that uses redis to create a temporary timed lock:
https://github.com/AlexDisler/MutexLock
The servers should be identical and have the same cron configuration. The server that will be first to create the lock will also execute the task. The other servers will see the lock and exit without executing anything.
For example, in the php file that executes the scheduled task:
MutexLock\Lock::init([
'host' => $redisHost,
'port' => $redisPort
]);
// check if a lock was already created,
// if it was, it means that another server is already executing this task
if (!MutexLock\Lock::set($lockKeyName, $lockTimeInSeconds)) {
return;
}
// if no lock was created, execute the scheduled task
scheduledTaskThatRunsOnlyOnce();
To run the tasks in a de-centralized way and spread the load, take a look at: https://github.com/chrisboulton/php-resque
It's a php port of the ruby version of resque and it stores the data in the same exact format so you can use https://github.com/resque/resque-web or http://resqueboard.kamisama.me/ to monitor the workers and see reports
|
I'm looking for better solution to handling our cron tasks in a load balanced environment.
Currently have:
PHP application running on 3 CentOS servers behind a load balancer.
Tasks that need to be run periodically but only on a single machine at a time.
Good old cron set up to run those tasks on the first server.
Problems if the first server is out of play for whatever reason.
Looking for:
Something more robust and de-centralized.
Load balancing the tasks so multiple tasks would run only once but on random/different servers to spread the load.
Preventing not having the tasks run when the first server goes down.
Being able to manage tasks and see aggregate reports ideally using a web interface.
Notifications if anything goes wrong.
The solution doesn't need to be implemented in PHP but it would be nice as it would allow us to easily tweak it if needed.
I have found two projects that look promissing. GNUBatch and Job Scheduler. Will most likely further test both but I wonder if someone has better solution for the above.
Thanks.
|
Cron Tasks on load balanced web servers
|
As explained here, it can be due to the lack of knowledge from the cron session shell of the ssh agent.
If that is the case (ie if you are using private ssh keys with a passphrase), keychain is the usual solution (as mentioned here).
More details in this example: "Passwordless connections via OpenSSH using public key
authentication, keychain and AgentForward".
|
I'm trying to run a git push from cron. When I do the command interactively on the shell it's going through fine. When running the command from my user's crontab, cron delivers the error message
Permission denied (publickey).
I presume it hasn't to do with finding or reading my ~/.ssh/id_rsa, as I can cat the file from cron alright. UID and EUID are set fine in the cron job. - Any ideas?
UPDATE
I got it working when supplying the environment key SSH_AUTH_SOCK to my cron job, but I'm concerned that this is only valid as long as I'm logged in. I'm looking for a solution that works independent of interactive logins.
|
git push via cron
|
Ensure that the cron service is running. I use WSL with cron every day for my local backups using rsync so this should work.
Use which cron to check its installed, mine says /usr/sbin/cron.
Use crontab -l to list your configured jobs.
Use ps aux | grep cron to look see if cron is running, you should see /usr/sbin/cron if it is.
Use service cron status to check if the service is started.
Use sudo service cron start to start the cron service if it is not running.
|
I set up some cronjobs a while back using crontab -e. My crontab includes the following line:
* * * * * /usr/bin/touch /home/blah/MADEBYCRON
It's been weeks since I did this. I have never seen /home/blah/MADEBYCRON. I set permissions on my home directory so it should be able to create files in this directory, so why does this file never exist?
/var/log/syslog does not exist.
|
Crontab never executes in Windows Subsystem for Linux
|
25
Please use:
import org.springframework.scheduling.support.CronSequenceGenerator;
final String cronExpression = "0 45 23 * * *";
final CronSequenceGenerator generator = new CronSequenceGenerator(cronExpression);
final Date nextExecutionDate = generator.next(new Date());
...and then I suggest use Joda DateTime for date comparison.
Share
Improve this answer
Follow
answered Dec 15, 2015 at 13:22
MattMatt
52911 gold badge55 silver badges1010 bronze badges
4
Excellent! Thank you very much!
– DmitryKanunnikoff
Jun 23, 2017 at 23:53
Spring implementation of cron actionally lacks one feature - 'day' and 'day-of-week' fields are combined by AND logic, not by OR as in cron.
– Eugene
May 28, 2018 at 13:37
@Eugene i don't think tat this is a disadvantage... you can easily simulate "OR"-ed expressions by providing 2 expression. With AND you have the advantage that you can execute e.g. "every 2nd thuesday at..."
– Michael Mangeng
Jun 26, 2018 at 15:07
2
Deprecated: need to use CronExpression generator = CronExpression.parse(cronExpression)
– myborobudur
Sep 20, 2022 at 15:56
Add a comment
|
|
my database having 10 18 16 ? * SUN,MON,WED,FRI * cron expression then how to convert into Java date.
how to comparing with present day time.
and one more is how to compare to cron expressions i.e. 10 18 16 ? * SUN,MON,WED,FRI * and 0 30 9 30 * ?
please explain the sample code using quartz or spring scheduling.
|
cron expression parsing into java date
|
Of course there is a difference!
0 * * * * - is every hour, when minute == 0.(i.e. 1:00, 2:00,..)
* * * * * - is every minute
Check out the guide for more info.
|
In Jenkins we have the Poll SCM schedule set to * * * * *. But Jenkins suggests Do you really mean "every minute" when you say "* * * * *"? Perhaps you meant "0 * * * *"
Is there any difference between * * * * * and 0 * * * * ?
|
Jenkins cron format
|
The docs you link to give examples of how you could achieve all of the results you want.
# Daily:
every day 00:00
# Weekly:
every monday 00:00
# Monthly:
1 of month 00:00
# Yearly:
1 of jan 00:00
|
I'm trying to set an appengine task to be repeated at midnight of every day, week, month, and year, for clearing a high score list for a game.
My cron.yaml looks like this:
- description: daily clear
url: /delete?off=10
schedule: every day 00:00
- description: weekly clear
url: /delete?off=20
schedule: every monday 00:00
- description: monthly clear
url: /delete?off=30
schedule: every month 00:00
- description: yearly clear
url: /delete?off=40
schedule: every year 00:00
Daily and weekly jobs are OK, but I can't figure out how to make a job repeat every month and year. This is the schedule format.
For each month job, I've tried expressions like 'every month', '1st of month', etc, but nothing did work. Is this type of schedule possible in cron jobs?
Or do I need to just invoke the clearing page just daily at 00:00, and do this logic in page and test current date, if it's the start of week/month/year?
|
Every day,week,month,year in AppEngine cron (python)
|
I had mistakingly thought that cron.yaml would be deployed as a cron job when I executed gcloud app deploy
To deploy the cron job I had to explicitly deploy cron.yaml
gcloud app deploy cron.yaml
|
I created a Google Cloud function that gets data and dumps it into a Google SQL Database. I need this function to execute every 15 minutes. As I understand it you cannot execute cloud functions in a cron job. The workaround is to deploy an app in the App engine.
I've deployed a simple NodeJS application that makes an http request using the NodeJS https module. I've deployed this app to Google App Engine along with the following cron.yaml
cron:
- description: "Gets new data every 15 minutes"
url: /
schedule: every 15 mins
But this is not executing and it is not showing up in the cron jobs list. Does the above cron job syntax look correct?
Is there anything else I need to do to get Google App Engine to pick up this cron job?
tyia
|
Google App Engine cron job not showing up
|
0 0 */5 * * midnight every 5 days.
See this, similar question just asked for every 3 days.
Cron job every three days
|
I want to setup cronjob which will start on for example today and it will run every 5 days.
This is what I have now, is this will work correctly ? If I install this job at 5 o`clock and then every 5 days on 6 AM.
0 6 */5 * * mailx -r [email protected] -s "Message title" -c "[email protected]" [email protected] < body.txt
|
How to setup cron job to run every 5 days?
|
The simplest solution here would be to have two entries in your crontab--one for the 30s and another for the 31s, e.g.:
0 0 30 6,9 * /path/to/your/script
0 0 31 3,12 * /path/to/your/script
|
Can anybody give a pattern on how do i run a cron job on quarterly basis. These include the dates March 31, June 30, September 30, Dec 31.
|
Crontab - Run a cronjob quarterly
|
From man curl:
--snip--
-m, --max-time <seconds>
Maximum time in seconds that you allow the whole operation to take. This is useful for preventing your batch jobs from hanging for hours due to slow networks or links going down. Since 7.32.0, this option accepts decimal values, but the actual timeout will decrease in accuracy as the specified timeout increases in decimal precision. See also the --connect-timeout option.
If this option is used several times, the last one will be used.
--snip--
-s, --silent
Silent or quiet mode. Don't show progress meter or error messages. Makes Curl mute. It will still output the data you ask for, potentially even to the terminal/stdout unless you redirect it.
|
I have found following in crontab
* * * * * sleep 5; curl -s -m 10 http://url > /dev/null 2>&1
* * * * * sleep 10; curl -s -m 10 http://url > /dev/null 2>&1
* * * * * sleep 15; curl -s -m 10 http://url > /dev/null 2>&1
* * * * * sleep 20; curl -s -m 10 http://url > /dev/null 2>&1
* * * * * sleep 25; curl -s -m 10 http://url > /dev/null 2>&1
* * * * * sleep 30; curl -s -m 10 http://url > /dev/null 2>&1
* * * * * sleep 35; curl -s -m 10 http://url > /dev/null 2>&1
* * * * * sleep 40; curl -s -m 10 http://url > /dev/null 2>&1
* * * * * sleep 45; curl -s -m 10 http://url > /dev/null 2>&1
* * * * * sleep 50; curl -s -m 10 http://url > /dev/null 2>&1
* * * * * sleep 55; curl -s -m 10 http://url > /dev/null 2>&1
so whats the meaning of curl -s -m 10 here ?
|
whats the meaning of curl "-s" and "-m"
|
Yes, cronjobs can run at the same time, and will do so if you set them up that way.
A 1 minute gap between each of the jobs might work, but what if one of them takes longer than a minute to run?
I would recommend explicitly calling them all in order:
0 * * * * joba.sh && jobb.sh && jobc.sh && jobd.sh
Note that this has the additional advantage of only calling the next job in the sequence if the previous one finished successfully.
|
What happens if I task the machine to run 4 cronjobs at the same time period say
0 * * * * joba.sh
0 * * * * jobb.sh
0 * * * * jobc.sh
0 * * * * jobd.sh
Will they be run one after each other independent of time itself or execute all at that point in time? These 4 jobs consequently in my case depend on each other so I was thinking of giving them a 1min between each of them i.e 0 1 2 3.
What do you think?
|
Multiple cronjobs at the same time
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.