Response
stringlengths 8
2k
| Instruction
stringlengths 18
2k
| Prompt
stringlengths 14
160
|
---|---|---|
Without more knowledge about your particular setup/system, and the fact that all jobs get executed multiple times, I can only surmise that you have multiple cron daemons running on your system.Do a full process list and grep forcron(most of them have that word in the name of the binary) and see how many are running. On a standard linux system, this should work:ps aux | grep cronThen you would have to figure out which should be running and kill the others.ShareFollowansweredJun 3, 2014 at 10:55fredrikfredrik6,55833 gold badges3737 silver badges4747 bronze badges4I can kill for today,what if cron is executing multiple time on daily basis–Neha ManglaJun 3, 2014 at 11:13If you kill the process it might stay dead until system restart. The bigger question is, why does your system have two cron daemons? It's one of those processes of which "there should be only one". Sort of like udev... Having more can, as you've seen, lead to undesired and/or unpredictable behaviour.–fredrikJun 3, 2014 at 11:16The only reason for two cron daemons running at the same time is because you or someone else installed and/or started them.–fredrikJun 3, 2014 at 11:502I got this root 17115 0.0 0.3 31748 3236 ? Ss 12:33 0:00 /usr/sbin/cron -f ubuntu 17320 0.0 0.1 14856 1024 pts/0 S+ 12:36 0:00 grep --color=auto cron What does this means can you please explain? @fredrik–Kshitij SharmaJul 30, 2020 at 12:39Add a comment|
|
I have set up a cron job that need to be executed once a day but it is getting executed multiple times.I have set up it as I mentioned below:5 8 * * * /sh_file_pathCan anyone please tell me why is this happening and what should I do to resolve this problem.
|
why my cron job executing multiple times?
|
The cronjob is running just fine, but the cron daemon (daemons in general as far as I know) have no access to stdout so cannot output messages to the terminal.To test it you can, however, output what you want to a file using*/1 * * * * echo "job every minute" >>$HOME/filenamewhich will output (and concatenate) the text to a file named "filename" in your home directory every minute.ShareFolloweditedJul 4, 2013 at 6:00answeredJul 4, 2013 at 5:55Ken HerbertKen Herbert5,21655 gold badges2828 silver badges3737 bronze badges4I tried this fix, and it is not saving the output to my home directory.–MEricJul 4, 2013 at 6:06Actually, I updated it in the crontab -e and it worked! Now I'm trying to run a python script (crontest.py) defined as follows: #!/usr/bin/env python print("test") The script is saved in my home directory, and I have modified my cronjob to the following: */1 * * * * $HOME/crontest.py However, it is not printing anything to the console. Any suggestions? Sorry I'm not sure how to get the code blocks in comments!–MEricJul 4, 2013 at 6:25make sure your python file is executable. also it will still not print to any terminal. you have to do the redirection as before.–mnagelJul 4, 2013 at 17:43Cron's do NOT print to console, but they can output to files–JonathanApr 14, 2015 at 22:20Add a comment|
|
I am new to using crontab, and I've been trying to get a simple cron job working. The code for the cron job is as follows:*/1 * * * * echo "job every minute"So just for proof-of-concept, I want to see this printed every minute. I have tried saving this cron job using bothsudo crontab -eand by saving a crontab file (cronscript) in a directory and enabling the script as follows:crontab ~/Documents/MyProjects/cronscriptwhich is the path for where the cron job is located.
Both of the identical jobs are saved properly, as I have verified by typingsudo crontab -eand
crontab -einto terminal and they both appear. I made sure there was a new line character saved after each command, and I checked to make sure cron is running by usingpgrep cronHowever, I am still not getting "job every minute" printed to terminal (every minute) which is what I believe these commands should be doing.What am I doing wrong? Thanks for the help!
|
Cron Job Doesn't Run
|
So far I've found 3 ways to do cron jobs BUT they all require some level of managing the multiple instances possibly running the tasks.The choices I've used so far:Windows Task Scheduler - create a startup script that adds the user and task the schedules it. More information here:Running Azure startup tasks as a real userand here:Building a Task Scheduler in Windows AzureUsing Quartz.Net - this I started with, but then moved to the windows task scheduler, but it may work for you since you can customize stuff easier. More information here:Using Quartz.net to Schedule Jobs in Windows.Azure Worker RolesUsing the new job scheduler in Mobile Services. I have not used this one, but when I read this blog:Job Scheduling in Windows Azurelate last year I put it on my mental list to look at next time I need a job scheduler. It's still a little new, but it also may help you.ShareFolloweditedApr 6, 2013 at 11:40answeredApr 6, 2013 at 11:35Jason HaleyJason Haley3,7801818 silver badges2222 bronze badgesAdd a comment|
|
I am developing an ASP.NET application, which will be uploaded on Azure. If I have multiple instances on Azure and I want to run a cron job that will be necessary for my application. Then, I just want to confirm if that cron job will be run only one time or each instance will run that cron by itself?For example: If I have 4 instances of cloud service on Azure and my application runs a cron job every day at 11:00 PM. So, I just want to confirm if that cron will be run only one time or each instance will run that cron on its own (i.e. cron will be run 4 times or we can say one time by each instance)?Please suggest.
|
Does each azure instance run cron?
|
It seems that anacron is no longer available for macOS, or never was at all according to this comment:https://apple.stackexchange.com/a/227308/176514I'm afraid you may need to take a look at launchd. More about that here:How do I set a task to run every so often?EDIT:
After some searching, it seems that this link has the latest version, made for 10.4 Tiger. I'm not sure that will work with Yosemite, but it is worth a shot.https://web.archive.org/web/20100723043612/http://members.cox.net/18james/anacron-tiger.htmlShareFolloweditedMay 23, 2017 at 12:09CommunityBot111 silver badgeansweredMar 7, 2017 at 17:23cdignamcdignam1,43511 gold badge1616 silver badges2121 bronze badgesAdd a comment|
|
I'm running Mac OSX 10.10, Yosemite, and am trying to set up an anacron job that runs a python script weekly.My anacron tab is as follows:# /etc/anacrontab
#period delay job-identifier command
7 10 cron.test /absolute/path/to/my/doc/test.pyNothing happens when I run sudo anacron -fn, and no timestamp file is created when I run anacron -u. The python script is executable, and I've included #!/usr/bin/env python at the top. How can I fix this and get anacron to run?P.S. - As an aside, I would prefer not to use launchd. What kind of program accepts its inputs in a pseudo-XML format in 2017??
|
Is anacron deprecated for Mac? How come I see no output when I run anacron?
|
Cron does only runonceat specific time or every minutes/hours/days etc. It doesn't check the return code. So it's not that easy peasy lemon squeezy at all...In my opinion you have a few options how to do it:Create a some kind of scheduler where you can write your CRON job again if it fails, in this case you will need one more CRON job to read you scheduler and run proper command. Scheduler can be database / file / NoSQL based. In scheduler you can have flag like(bool) executedwhich will let scheduler know which tasks are already done.Use queues (f.ex. Rabbit) to call it self again when fail.Use framework, I'm using Symfony to manage own created commands to execute them (check second link below) based on database, using also enqueue/enqueue-bundle package to manage queues in Symfony.I think if you are not so advanced with PHP I'd recommend to go for self made scheduler based on database (MySQL / PostgreSQL / NoSQL) with Symfony (check second link below). In this case you just have toSELECTall non executed record (commands) from database and just run them.LectureLaravel - Queues, retrying failed jobsSymfony - calling another commands in commandQueues package for PHP (incl. Symfony)enqueue/enqueue-bundleShareFollowansweredDec 31, 2019 at 18:54Karol GasienicaKarol Gasienica2,8652626 silver badges3636 bronze badgesAdd a comment|
|
I have a cron job that run every 5 Hours. It calls aPHPscript , this script will do a call to an external API to sync some data.The problem is sometimes I'm getting timeout from the API and the job will fail.Are there any mechanisms to let cron tab do auto retry or auto recover the jobs that are failed?I have tried to do an extra job and call it in case of any failures manually.What is the best approach to do so?
|
Cron job auto retry if any job get failed
|
+25"application error 5" means that the request deadline was exceeded.You can increase the deadline for the request by using the option CURLOPT_TIMEOUT, so you code might look something like:$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60); // 60 second timeout
$output = curl_exec($ch);ShareFollowansweredJul 21, 2015 at 0:42Stuart LangleyStuart Langley7,05411 gold badge2121 silver badges2020 bronze badgesAdd a comment|
|
Background:I am using google app engine and am having a weird bug in my site crawler.I have a backend that will automatically crawl a site every night. This is instigated by a task pushed to a pushQueue due to time limits in php.Problem:When I manually run the script that creates the task, the task completes as expected with no errors. However when cron launches the task I get the following error.Call to URLFetch failed with application error 5 for url xCode:function url_get_contents ($Url) {
global $retry;
try {
if (!function_exists('curl_init')){
die('CURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
return $output;
} catch (Exception $e) {
syslog(LOG_INFO, 'Caught exception: ', $e->getMessage());
if($retry > 0){
$retry -= 1;
return url_get_contents($Url);
}
else{
return null;
}
}
}Thanks to syslog I can see that the $url is fine which is driving me crazy as it works when the exact same script is launched manually not through cron.How can I fix this?Thanks in advance.
|
Call to URLFetch failed with application error 5 for url x
|
That error is generated when App Engine needs to shut your backend down but the backend fails to exit within 30 seconds. Some reasons why this might be happening are listedhere. Depending on the type of error, App Engine may be sending your backend a notification of the impending shutdown, so it's a good idea toregister a shutdown handlerso you can gather more data about your app's state when this is about to happen.If you are seeing this regularly there is probably a systematic explanation, such as your job's memory exceeding the maximum for the backend's class.ShareFollowansweredOct 5, 2012 at 5:11Adam ThomasonAdam Thomason99311 gold badge88 silver badges1010 bronze badges1Adding the sutdown handler did not help in my app. I am using python2.7 webapp with a backend. Appengine shows this message in the logs 95% of the time. The handler got invoked only 2-4 times over the last week. When it did get invoked the backend did work to finish. Logging the memory and processor usage shows well within limits. Shutdown handlers are not guaranteed to be called as from a google io talk on backends.–quiet_penguinDec 5, 2013 at 8:07Add a comment|
|
My backend job is working on the basis of cron job(every 4 hour).But it is terminated with out processing the data. The server log displays as following :500 15377121ms 0kb instance=0 AppEngine-Google; (+http://code.google.com/appengine)
E 2012-10-05 01:50:18.044 Process terminated because the backend took too long to shutdown.How to handle this kind of error in my program
|
GAE :Process terminated because the backend took too long to shut down in backends job
|
As @The.Anti.9 noted, this kind of question fits in Serverfault.
To answer your question, crontab is a little more powerful than 'at' and gives you more flexibility as you can run the job repeatedly for instance daily, weekly, monthly.For instance for your example, if you need to run the script every day at 18:30 you'd do this,$ crontab -ethen add the following30 18 * * * /path/to/your/script.shsave and you are done.Note: 30 18 indicates time 18:30, and *s indicate that it should run every day of every month) If you need to run it on a particular day of the month just check it out on the man page of crontab.ShareFollowansweredDec 7, 2011 at 9:07Kibet YegonKibet Yegon2,80322 gold badges2525 silver badges3232 bronze badges3what do I do, if I want it to run at several specific times a day e.g. 9:00, 12:00 and 18:30 o'clock ? create 3 cronjobs or can I specify it in one?–veritaSAug 29, 2018 at 7:09@veritaS If the time duration between them is the same (say every hour) then one crontab is sufficient. If its not like your case, you'd need to have 3 entries. Check the crontab manpage or usethis generator–Kibet YegonSep 6, 2018 at 8:531I currently have it running with comma seperated values. You can do something like 30 5,11,18 * * * /path/to/your/script.sh which translates to at 5:30, 11:30 and18:30–veritaSSep 9, 2018 at 1:04Add a comment|
|
I am using the amazonaws es3 server.I want to schedule my cron with command line.
I am using the this command for scheduling the cron jobat -f shellscript.sh -v 18:30but it will schedule for only one time i want to configure manually like once a day or every five minutes .Please help with command which command i have to usedThnaks,
|
Schedule a cronjob on ssh with command line
|
You can find some more information on making CodeIgniter CLI-accessible here:http://phpstarter.net/2008/12/run-codeigniter-from-the-command-line-ssh/Next step is just using crontab -e to set up the cronjob.ShareFollowansweredFeb 10, 2010 at 12:46Zack EffrZack Effr9144 bronze badgesAdd a comment|
|
I am using codeigniter. I want to know how to set up a cron job to check a table for expiring users and insert data in to another table with the list of expiring users. How to do that.When i tried to write a script with controller and model to insert the table:Fatal error: Class 'Controller' not found in/home/content/html/test/live/application/controllers/cron.phpon line2
|
CRON job for codeigniter
|
+25There is currently no such functionality to generatecronexpressions inLater.js. All cron-related functionality has to do with parsingcronexpressions, not generating them. You can confirm this by looking at all usages of the wordcronin the master branch of theLater.jsrepository on GitHub. Here is a link to the search:https://github.com/bunkat/later/search?p=1&q=cron&type=&utf8=%E2%9C%93ShareFolloweditedDec 31, 2017 at 18:02answeredDec 29, 2017 at 6:04JMAJMA1,8091010 silver badges1818 bronze badgesAdd a comment|
|
We are storing schedules as cron expressions in database. The schedules are modified in a web page and I'm using Later.js for this. Works great to parse the Cron expression. Now I would like to output the modified schedule to a Cron expression that can be stored in database.Is there any "toCronExpression" function in Later.js?I know I can read the properties of the schedule object and output them myself but I was hoping for a built in function.
|
Getting Cron Expression from Later.js
|
You can specify days of the week withDailyTimeIntervalScheduleBuildervar onMondayAndTuesday = DailyTimeIntervalScheduleBuilder.Create()
.OnDaysOfTheWeek(new DayOfWeek[] { DayOfWeek.Monday, DayOfWeek.Tuesday });
var trigger = TriggerBuilder.Create()
.StartAt(DateBuilder.DateOf(StartHour, StartMinute, StartSeconds, StartDate, StartMonth, StartYear))
.WithSchedule(onMondayAndTuesday)
.WithCalendarIntervalSchedule(x => x.WithIntervalInWeeks(Int32.Parse(nWeekInterval)))
.EndAt(DateBuilder.DateOf(0, 0, 0, EndDay, EndMonth, EndYear))
.WithIdentity(triggerKey)
.Build();ShareFolloweditedMar 30, 2015 at 10:03answeredMar 30, 2015 at 9:53Nick PatsarisNick Patsaris2,16811 gold badge1717 silver badges1919 bronze badges12This is invalid code. You can't specify two different kinds of schedule (daily and calendar here).–Piotr PerakApr 26, 2017 at 20:25Add a comment|
|
I used the below way to run the schedule on every two weeks on mondays.ITrigger trigger = TriggerBuilder.Create()
.StartAt(DateBuilder.DateOf(StartHour, StartMinute, StartSeconds, StartDate, StartMonth, StartYear))
.WithCalendarIntervalSchedule(x => x.WithIntervalInWeeks(Int32.Parse(nWeekInterval)))
.EndAt(DateBuilder.DateOf(0, 0, 0, EndDay, EndMonth, EndYear))
.Build();But how can I use a single schedule to run on mondays and tuesdays as well. Please advice.
|
How can I run a quartz schedule on mondays and tuesdays every two weeks?
|
The job may run, but probably won't complete. cron is implemented via a daemon, so it's always running. Depending on your system's shutdown order, cron may actually be sent the shutdown signal fairly late in the shutdown process, so jobs scheduled for the moment the shutdown started may still run.e.g. If the shutdown starts at 00:00:00 exactly, but doesn't get to sending cron a kill signal until 00:00:05 (5 seconds after midnight(, then a short running 2-second job may still have time to complete.However, if any services that job depends on have already been shutdown or are in the process of shutting down, then it's unlikely to be able to finish. e.g.... the script pings a mysql server for one little piece of data... but mysql shut down at 00:00:01 and your script didn't get to the mysql portion until 00:00:02.tl;dr: it's a race condition and your job MAY execute, but probably won't.
|
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed12 years ago.Improve this questionFrom man page of crontab.string meaning
------ -------
@daily Run once a day, "0 0 * * *".
@midnight (same as @daily)So a job @daily will never be executed if the system is always shutdown at midnight? What is the proper way to specify that I want to run this job once daily but I don't care when exactly it is executed in a day?
|
What happens to cron jobs when system in shutdown? [closed]
|
+100Phpseclib should do just fine transferring big files with no need to increase available memory.I think you probably hit the old bug "SSH2: don't count data length against window size". You most likely may be using older version of the Phpseclib ( The older faulty version is bundled even with relatively new software like for example Magento 1.9.* )Check your version if is not the latest redownload it fromhttps://github.com/phpseclib/phpseclib
|
I have a large file (200 MB upwards). I need to transfer it via PHP cron job. UsingPhpseclibgives the following error:Allowed memory size of 134217728 bytes exhausted (tried to allocate
4133 bytes) in /app/vendor/phpseclib/phpseclib/phpseclib/Net/SSH2.phpIs there a way I can do this withPHP cron job?The code is simple one line where $localFile is an already existing CSV file$sftp->put('/Import/coupons/coupons_import_test.csv', $localFile, NET_SFTP_LOCAL_FILE);PS. This needs to be done afterPHPgenerates that file in the/tmpfolder so timing of the transfer script has to come into play.[Edit]
I do not intend on increasing the memory limit as the files later could be of higher sizes. A solution where I can transfer the file in parts (append mode) or use some shell script with PHP cron could be worthwhileThe file size on remote server is 111.4 MB while the actual file is much larger on local.[Edit after the fix]
The issue disappeared after changing to version 2.0.2 from version 1.0
I had to modify the code for put$sftp->put('/Import/coupons/coupons_import.csv', $localFile, $sftp::SOURCE_LOCAL_FILE);
|
Transfer large file via SFTP in PHP
|
There now is a Debian bug reported (andfixed) about this.It mentions about a release to stable:In the next security upload, e.g. roughly two weeks after 5.6.23 is
released, unless something else critical shows up.5.6.23 is out, so I expect it within the next two weeks.The fix there is to addif [ -d "/proc/$pid/fd" ]; thenbefore thefind "/proc/$pid/fd"command.
|
After PHP upgrade I started to get the following cron errors several times a day:find: `/proc/xxxxx/fd': No such file or directoryIt comes from PHP sessionclean cron job:[ -x /usr/lib/php5/sessionclean ] && /usr/lib/php5/sessioncleanAny ideas?
|
Cron sessionclean errors: find: `/proc/xxxxx/fd': No such file or directory
|
Use the functionapply().Documentation forapply().
|
I have a simple periodic task:from celery.decorators import periodic_task
from celery.task.schedules import crontab
from .models import Subscription
@periodic_task(run_every=crontab(minute=0, hour=0))
def deactivate_subscriptions():
for subscription in Subscription.objects.filter(is_expired=True):
print(subscription)
subscription.is_active = False
subscription.can_activate = False
subscription.save()And I want to cover it with tests.I found information about how to test simple tasks, like @shared_task, but nowhere can I find an example of testing@periodic_task
|
How to test celery periodic_task in Django?
|
Cron tables are in deed the appropriate solution. Rewriting crontable in PHP would be both painful and uncertain on scheduling, unless you choose to use the fork functions, making it even more painful to write.Launching the PHP script is pretty straight forward with wget, which gives you a bunch of logging utilities. Themselves being log rotatable for instance.You should definitely share some job-tools.sh among your jobs scripts to always report their malfunctions, step by step.Concerning the PHP script execution itself, you'd better rely on your standard PHP error log, which you probably already watch.Cheers,
|
I am using crontab as the manager for administrative scripts and set up each job manually. Which seem to be very straight forward and perhaps ideal solution.Problem that I realized is, that I don't have any unified and automated control whether those scripts run fine all the time. Some of them are quite old... some are configured to send emails if problem occurs, others writes to custom error logs...My plan is to unify all job scripts to strictly return correct status codes so I can just analyze crontab log (or custom log via "2>") for issues. Perhaps even write some very simple job framework which will assert the unification and automate things for my needs...Would you suggest some best practices? Or anything else? Or something to read about the topic before I start?Thanks
|
Php scripts (jobs) architecture. Is cron the ideal solution?
|
Second approach is better (use heroku scheduler if on heroku), queues are more for "run as soon as possible" than "run at this particular datetime"
|
I'm building a reservation system in Rails 4.2 where I need to send a set of emails to users at predefined intervals (for example that they have an upcoming reservation, feedback after it's done, a link to change/cancel an existing reservation, etc.). I've looked around and foundthisandthis, but I'm trying to decide between the approaches.I see two main ways of building this system out.Using a queue system likedelayed_job. Whenever someone makes a reservation, we queue up all the emails for the correct time when they should be sent.Pro: One queue for all emails. Automatic retry logic.Con: Thousands of emails will eventually get queued in the system. Need to dequeue whenever someone cancels a reservation (dependent: destroy emails related to it might be pretty easy). Somewhat more complex logic around what time we need the emails to go out.cron+raketask that runs at some predefined interval (hourly? every fifteen minutes?) and checks for the emails that need to go out. It runs a query like "Find all reservations that are three days from now", and then sends out all emails.Pro: Put everything into application logic, reduce the amount of state we need to keep track of.Con: Need to keep track of which emails have been sent, which is conceptually similar to whatever jobs table we already have created above.
|
Architecting a system for reminder emails
|
Under centos 7, provided the "extras" repo is enabled, you can just runyum -y install epel-release. I'm not sure this is available under Centos 6 (certainly won't hurt to try it). However, to install under CentOS 6 manually you would just run (as root, or using sudo):wget https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm
rpm -Uvh epel-release-6*.rpmOnce the EPEL repository is installed on your system, try runningcertbotagain. It should now be able to automatically install any required dependencies.
|
I use certbot-auto for deploying Let's Encrypt SSL certificates, and I renew certificate with crontab -e like this:* 01 * * 1 /home/myname/certbot-auto --quietIt has an error message like the below:Bootstrapping dependencies for RedHat-based OSes...
yum is /usr/bin/yum
To use Certbot, packages from the EPEL repository need to be installed.
Please enable this repository and try running Certbot again.I can't solve this error. Please help me!
|
To use Certbot, packages from the EPEL repository need to be installed
|
Not quite what you asked, but maybe what you want isos.isatty(sys.stdout.fileno()), which tells ifstdoutis connected to (roughly speaking) a terminal. It will be false if you pipe the output to a file or another process, or if the process is run from cron.
|
I would like to know how can I determine if a python script is executed from crontab?I don't want a solution that will require adding a parameter because I want to be able to detect this even from an imported module (not the main script).
|
How can I determine if a python script is executed from crontab?
|
In 2.3.0.2 a very simple way I found was to add your controller function path into the ignored paths settings for login and permission restrictions. Then just add a url password or other check in that controller function to lock it down.So first in admin/controller/startup/login.php add your controller function path to both $ignore arrays, eg 'common/cron/action'And then in admin/controller/startup/permissions.php you want just the controller path, eg 'common/cron'And then finally at start of your action() function do like:if(!isset($_GET['pass']) || $_GET['pass'] != 'secretpassword')return;Then i just added this to my cron:php-cli -r 'echo file_get_contents("https://www.website.com/admin/index.php?route=common/cron/action&pass=secretpassword");'
|
I know about CRON and how to create/manage it. But this issue was different.I want to develop a module to delete any (unpaid) order that exceeds the time frame given.
Ex: I want to delete any unpaid order that has not been paid for 2 days after the order was placed.I want to use existed model in opencart (and not use a new one). Let's say the module URL would be:http://www.yourstore.com/admin/index.php?route=module/modulename/functionAnd will be called from CRON, and then all any unpaid order will be disappeared.But the main problem is: when CRON wants to access that URL, it needs a security token or it will never be executed.My question is: how to execute that module from CRON without security token (in case just for that module)?Please help me, if you have a better idea or a more clean way, I would say many thanks to you.
|
Opencart Admin Cron Jobs
|
This can be done this way:every :hour, at: 0 do #task 1
every :hour, at: 10 do #task 2
every :hour, at: 20 do #task 3
|
I have a bunch of cronjobs managed by whenever. Everything works fine, but I have a few hourly cronjobs that are all triggered at the same time, so I'd like to stagger them. Worst case scenario I'm able to update the crontab manually, but I'd really rather take of this in schedule.rb.TL;DR - I would like to do something like:every 1.hour, at: ":00" do #task 1
every 1.hour, at: ":10" do #task 2
every 1.hour, at: ":20" do #task 3Thanks!
|
whenever gem: hourly tasks with minute set
|
I'm responding by myself just because none answered.0 * * * * timeout -s 9 3540 /path/to/your_command.shwill send a SIGINT to your command if it hasn't completed in 59 minutes.
|
I have a scheduled cron job (which is actually a shell script). I'd like to limit the script execution time as it can work unacceptably long. For some reason I can not limit the script execution time from inside the script. Actually, I want my system to force the task termination if it runs more than N hours. Please advise.
|
How to limit shell script execution time?
|
You can add to your crontab something like0 * * * * /bin/bash -l -c 'cd /path/to/your/project && bundle exec rake foo:bar >> log/cron.log 2>&1'This will runfoo:bartask every hour and writestdoutandstderrtolog/cron.log.Please noticebundle execbeforerakecommand.Using bundler ensure you that task will fetch correct environment.To specifyRAILS_ENVyou can do... && RAILS_ENV=production bundle exec rake foo:bar
|
I have and rails application and a rake task which I'm going to execute by cron around once in an hour. But the thing is that the task uses rails environment and some classes of my rails application. If I run it as ruby script, I'll have to include all the dependencies it uses and I think it's not possible to do it correctly and in a simple way. So I'll have to run it as a rake task because it'll preserve all the dependencies, right? Then how can I run a rake task from cron?Note that I prefer not to use any third-party solution when there's no necessity, in this case I don't want to use the gem whenever or the like.
|
How can I run a rake task via cron?
|
This is exactly what Cron (linux) or Scheduled Tasks (windows) are for.You can run them on your application server to keep everything in one place.For example, I have a cron running on my home server to backup its MySQL databases every day. Only one system is involved in this process.
|
I have some functions that use curl to pull information off a couple of sites and insert them into my database. I was just wondering what is the best way to go about executing this task every 24 hours?I am running off windows now, but will probably switch to linux once I am live (if that makes a difference). I am working inside symfomy framework now.I hear cronjobs can do this this...but looking at the site it seems to work remotely and I would rather just keep things in house...Can i just "run a service" on my computer? whatever that means ;) (have heard it used)thanks for any help,
Andrew
|
running a php task every 24 hours
|
Advise 1: use wget command, wget runs the PHP script exactly as if it was called from the web so the PHP environment is exactly the same of when calling the file from the web, it's easier to debug your script then.wget -O - http://yourdomain.com/adi/cron/daily.php >/dev/null 2>&1The cron jobs has to be created going into cPanel cron jobs menu. I don't understand if you have this clear by reading your hoster's answer.And advise 2: change web hosting, trythis onethey don't leave you alone.
|
Hi I want to run a cron job to call a PHP script on my server.I am using Cpanelfrom my web host and these are the options:Minute:Hour:Day:Month:Weekday:Command:I am really struggling to point the command to my file I am using this line/home/abbeysof/public_html/adi/cron/daily.phpbut I am getting this error:/bin/sh: /home/abbeysof/public_html/adi/cron/daily.php: Permission deniedI asked my web host for help and this is the response:If you use cpanel to create it, it will fill in the path for you. Typically /home/username/public_html/etcCan anyone please offer some advice?
|
File path for a Cron Job
|
I recently ported the Quartz compatiblecron-expression-descriptorfrom C# to JavaScript and named itcRonstrue. This JavaScript library is able to convert a Quartz cron expression into a human readable string like this:cronstrue.toString("0 23 ? * MON-FRI");
> "At 11:00 PM, Monday through Friday"
|
I used below Javascript API to create Quartz compatible UI to provide cron expression to server side quartz sevices.https://github.com/felixruponen/jquery-cronDo we have any API , which we can use to convert cron expressions into human readable strings in Java Script.Thanks
|
JavaScript API that converts cron expressions into human readable strings
|
To get started with launchd (instead of cron) you'll want to first create an empty.plistfile, for examplelocal.mytask.plistand put it somewhere.~/Library/LaunchAgentsis probably a good place. Open that in text editor and copy in the code below<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>KeepAlive</key>
<false/>
<key>Label</key>
<string>local.mytask</string>
<key>ProgramArguments</key>
<array>
<string>/opt/local/bin/wget</string>
<string>http://someserver/somepage.php</string>
</array>
<key>StartInterval</key>
<integer>300</integer>
<key>RunAtLoad</key>
<true />
<key>StandardErrorPath</key>
<string>/dev/null</string>
<key>StandardOutPath</key>
<string>/dev/null</string>
</dict>
</plist>Then "activate" the file from the command line:sudo launchctl load /Users/my_username/Library/LaunchAgents/local.mytask.plistTo make it load automatically, create a~/.launchd.conffile with the same line (minussudo launch)load /Users/my_username/Library/LaunchAgents/local.mytask.plistThe above instructions above have been copied fromwww.davidlanier.comand reposted here for your reference.
|
I'm trying to get familiar with cron jobs, and I think I get the basic idea (scheduling, syntax, etc), But, I can't seem to get it right on my mac with Terminal - where exactly do I find the Crontab? How should I reference the paths to scripts?What I'm trying to do is hit a php script on a remote machine (http://...) - Is that possible at all?
|
Getting started with cronjobs on a Mac
|
For example, the description of crontab for deleting files older than 7 days under the/path/to/backup/every day at 4:02 AM is as follows.02 4 * * * find /path/to/backup/* -mtime +7 -exec rm {} \;Please make sure before executingrmwhether targets are intended files. You can check the targets by specifying-lsas the argument offind.find /path/to/backup/* -mtime +7 -lsmtimemeans the last modification timestamp and the results of find may not be the expected file depending on the backup method.
|
I am having issue storing my server backup on a storage VPS. My server is not deleting old backup folders and the storage is getting full and the backup fails in mid way. My runs once every week.Can anyone help me create a cron job script on that deletes folder older than 7 days and runs one day before backup and delete old folders.Any help appreciated.
|
Cron Job to auto delete folder older than 7 days Linux
|
* * * * * command to be executed
- - - - -
| | | | |
| | | | +----- day of week (0 - 6) (Sunday=0)
| | | +------- month (1 - 12)
| | +--------- day of month (1 - 31)
| +----------- hour (0 - 23)
+------------- min (0 - 59)Replace the*with the values you need.
|
How to identify that cron job will run on specific Date&Time with help of cron expression Only
|
PHP - Cron Job Run At Specific Date & time
|
This is a tricky problem. If you're running the PHP script via the command line, you can set the process's scheduling priority to low (start /low php.exe myscript.phpI believe). If your PHP script itself is actually doing most of the processing that's eating your CPU, this might work. However, you said you are doing some heavy database and filesystem interaction, which this solution will not help. It looks like there is a MySQL hint "LOW_PRIORITY" for INSERT and UPDATE queries that may help you there, but I have not tried those.
|
I have a scheduled task that runs a script on a regular basis (every hour). This script does some heavy interaction with the database and filesystem and regularly takes several minutes to run. The problem is, the server's cpu-usage spikes while the script is running and slows down normal operations. Is there a way to throttle this process so that it takes longer but does not consume as many resources?I've looked at different configuration options for PHP but there does not appear to be any that fit my needs.Setting memory_limit in php.ini to something lower causes my data objects to overflow quite easily.I've seen similar posts where people suggested using sleep() at certain points in the script but that does not prevent the script from spiking the server.The optimal solution would be some way to tell the Lamp (in this case Wamp) stack to only use 10% max cpu utilization. I'm not concerned at all about runtime and would prefer that it take longer if it means saving cpu cycles per second. My alternate solution would be to setup a different server with database replication so the cron could go to town without slowing everything else down.Environment: Windows Server 2k3, Apache 2.2.11, PHP 5.2.9, MySQL 5.1I appreciate any insight to this situation.EDIT:I appreciate all the answers, even the ones that are *nix-specific. It's still early enough in my situation to change the hosting environment. Hopefully this question will help others out regardless of the OS.
|
Suggestions/Tricks for Throttling a PHP script
|
You need to manually edit crontab:First:crontab -eand then add* * * * * php /home/vagrant/Code/soeptime/artisan schedule:run
|
I've created a command to send automatic emails. When I dohomestead sshand I runphp artisan emails.sendan email arrives in my mailtrap.io account.I've added this code to the kernel.php$schedule->command('emails:send')->everyFiveMinutes();I've put it at a 5 minute interval, just to make it easier to quickly test it.
I've ssh'd into Homestead and performedphp /home/vagrant/Code/soeptime/artisan schedule:run 1>> /dev/null 2>&1then Iexithomestead and I didhomestead provisionHowever, there is nothing in the logs and I still haven't received an email, homestead is now running for more then 15 minutes.
|
Cronjob Homestead not working
|
Had the same issue, you need to specify the full path when you callgsutil.
In your case:/usr/local/bin/gsutil/gsutil cp /home/deploy/testfile.txt gs://testbucket/testfile_$now.txt;
|
gsutil has been installed here:/usr/local/bin/gsutilMy crontab looks like this (i'm logged in as root):*/1 * * * * /home/deploy/cron/job.sh >> /home/deploy/cron/test.log 2>&1job.sh:#!/bin/sh
PATH="$PATH":/usr/local/bin/gsutil
now=$(date +"%m_%d_%y_%R");
cp /home/deploy/testfile.txt /tmp/testfile_$now.txt;
gsutil cp /home/deploy/testfile.txt gs://testbucket/testfile_$now.txt;
echo "saved file at $now";When I look in my log file I see this:/home/deploy/cron/job.sh: 5: /home/deploy/cron/job.sh: gsutil: not found
saved file at 07_20_15_13:03Any idea what I'm doing wrong?
|
Cron - gsutil not found
|
please add below code in you file. where you have calledwp_mail()function.Add this code top of your file.require_once("../../../wp-load.php");or change your functionwp_mail()tomail()
|
Hi im using this function by Wordpress in a Cron webpage and is throwing this error on my emailFatal error: Call to undefined function wp_mail() in/home/meusite/public_html/wp-content/themes/escotec/page-cron.phpon line33Here the codeforeach($inscricoes as $key => $item){
$emailSent = false;
$emailTo = "$item->getEmail()";
//echo "..1";
$subject = '[Escotec]: Dados para pagamento de inscrição ';
$body = "Parabéns $inscricao->nome, sua inscrição no curso ".$item->getTurmas()[0]->getCurso()->getNome()." foi efetuada. <p>Para concluir o pagamento da inscrição clique no link abaixo ou cole-o diretamente na barra de endereços de seu Navegador: </p><br>";
$body .= "<a href=\"http://escotecnordeste.com.br/pagamento/?email=".$item->getEmail()."&pedido=".$item->getPagamentoId()."\" target=\"_blank\">http://escotecnordeste.com.br/pagamento/?email=".$item->getEmail()."&pedido=".$item->getPagamentoId()."</a>";
$headers = 'From: Escotec Nordeste <[email protected]>' . "\r\n" . 'Reply-To: ' . '[email protected]';
wp_mail($emailTo, $subject, $body, $headers);
$emailSent = true;
// http://escotecnordeste.com.br/pagamento/[email protected]&pedido=11
// Codificar envio do e-mail
if ($emailSent) {
// Atualizar registro do pedido para email_enviado = 'S'
InscricaoDAO::RegistraEnvioEmail($item->getPagamentoId());
}
}Ty for help
|
Call to undefined function wp_mail
|
EDITED:Try something like this:*/1 * * * * . /path-to-env/bin/activate && /home/user/Desktop/job/dp/manage.py statisticsThis should be read as: activate the env and if that was successful, excute the manage.py script. Since manage.py is supposed to have a python shebang and the virtual env sets the correct python interpreter, this should work.Apparently cron usually runs with/bin/shwhich does not know thesourcecommand. So one option is to use a dot as asourcereplacement. Another to set/bin/bashin the cron file:SHELL=/bin/bash
*/1 * * * * source /path-to-env/bin/activate && /home/user/Desktop/job/dp/manage.py statisticsRead more about this issue at:http://codeinthehole.com/writing/running-django-cronjobs-within-a-virtualenv/The article doesn't mention thatsourcecan be replaced by a., but i've just tried it and it worked for me. So you have several options to choose from now, the article even has others. ;)
|
How to run in crontab*/1 * * * * /home/user/Desktop/job/dp/ python manage.py statisticswith virtual env? I need to activate virtualenv first(Otherwise it does not work)This is my virtual env:source job/bin/activate
|
How to run custom manage.py in crontab + virtual env?
|
Your cron should change the working directory before running PHP:cd /var/www/vhosts/domain.com/httpdocs/app/protected/classes/cron/ && /usr/bin/php -q runner.phpNote that if the directory does not exist, PHP will not run runner.php.
|
I'm trying to setup a PHP file as a cron job, where that PHP file includes other PHP files.The file itself is located at /var/www/vhosts/domain.com/httpdocs/app/protected/classes/cron/runner.phpThe include file is at
/var/www/vhosts/domain.com/httpdocs/app/protected/config.phpHow do I include that config file from runner.php? I tried doing require_once('../../config.php') but it said the file didn't exist.. I presume the cron runs PHP from a different location or something.The cron job is the following../usr/bin/php -q /var/www/vhosts/domain.com/httpdocs/app/protected/classes/cron/runner.phpAny thoughts?
|
PHP include in a cron job
|
Try specifying the full path to the jar file:/usr/bin/java -jar /path/to/Pharmagistics_auto.jar -o
|
I have tried exporting my paths and variables and crontab still will not run my script. I'm sure I am doing something wrong.I have a shell script which runs a jar file. This is not working correctly.After reading around I have read this is commonly due to incorrect paths due to cron running via its own shell instance and therefore does not have the same preferences setup as my profile does.Here is what my script looks like today after several modifications:#!/bin/bash --
. /root/.bash_profile
/usr/bin/java -jar Pharmagistics_auto.jar -o
...those are the most important pieces of the script, the rest are straightforward shell based.Can someone tell me what I am doing wrong?
|
shell script not running via crontab, runs fine manually
|
According to RVM documentation:https://rvm.io/integration/cronFor every rvm or gemset there is an environment file which describes it. You can obtain it with:rvm env --path -- ruby-version[@gemset-name]That is the path to the environment file of rvm.It is a good habit when running rake tasks from cron, toinvoke them from a shell script.The crontab should be something like:*/30 * * * * /path/to/shell/script.sh >/dev/null 2>&1And then in the shell script :#!/bin/bash
cd /path/to/project
source /path/to/env/file
rake taskHope this helps!
|
I am trying to run a Rake task using crontab in Rails 3.0.9(using RVM), But it is not working.But when i running in the console it works fineMy Rake Tasknamespace :alert do
desc "create some reminder notification"
task :send_reminder => :environment do
p "my task goes here ----"
end
endMy cron task*/1 * * * * cd /home/anu-karthik/Documents/billguru/ && /home/anu-karthik/.rvm/gems/ruby-1.9.2-p0/bin/rake alert:send_reminder >/home/anu-karthik/alert.outBut I didn't found any log entry in "alert.out" filealso I have tried with following method*/1 * * * * cd /home/anu-karthik/Documents/billguru/ && rake alert:send_reminder >/home/anu-karthik/alert.outnow output is
(in /home/anu-karthik/Documents/billguru)I think it is the problem with RVM. How do I solve this issue?
Thanks in advance
|
rake task and cron in rails 3 with rvm
|
Check outGitLab schedules: it does mention:The pipelines won't be executed precisely, because schedules are handled by Sidekiq, which runs according to its interval.For example, if you set a schedule to create a pipeline every minute (* * * * *) and the Sidekiq worker runs on 00:00 and 12:00 every day (0 */12 * * *), only 2 pipelines will be created per day.To change the Sidekiq worker's frequency, you have to edit thepipeline_schedule_worker_cronvalue in yourgitlab.rband restart GitLab.
|
I try to set up a scheduled pipeline that runs every 20 mins. I use the customized cron syntax (*/20 * * * *) in the setting, but gitlab doesn't honor this and still runs it every hour.Is this a gitlab bug or did I miss something?
|
Is it possible to schedule gitlab pipeline in less than an hour?
|
Modify the script so it checks the current time, and bails out if it's not a multiple of 5 minutes.Something like this:#!/bin/bash
minute=$(date +%M)
if [[ $minute =~ [05]$ ]]; then
php ...
fiThe right operand of the=~operator is a regular expression; the above matches if the current minute ends in0or5. Several other approaches are possible:if [[ $minute =~ .[05] ]]; then(check for any character followed by a0or5;$minuteis always exactly 2 characters).(User theshadowmonkey suggests in a comment:if [ $(($minute % 5)) -eq 0 ]; thenwhich checks arithmetically whether$minuteis a multiple of 5, but there's a problem with that. In the expression in a$(( ... ))expression, constants with leading zeros are treated as octal; if it's currently 8 or 9 minutes after the hour, the constant08or09is an error. You could work around this withsed, but it's probably not worthwhile given that there are other solutions.)
|
I'm trying to run this script every 5 minutes. It seems the only way to run CRON jobs on OpenShift is to use their CRON plugin. And the CRON plugin only allows for minutely, hourly, and daily scripts (by placing the script in the corresponding folder).I am trying to run this script every 5 minutes:#!/bin/bash
php /var/lib/openshift/53434c795973ca1ddc000668/app-root/runtime/repo/scheduled.php > /dev/null 2>&1But right now it runs every minute (because it's placed in the minutely folder).How can I re-write it so that it runs every 5 minutes?
|
Run CRON job every 5 minutes on OpenShift (Red Hat Cloud)
|
,15,30,45 * * * * /bin/bash -l -c 'cd /var/www/apps/my_app/current && RAILS_ENV=production bundle exec rake thing:do_stuff --silent'
|
Stack:Apache2Rails 2.3.8RedHat LinuxRuby Enterprise 1.8.7Got the following rake task in my app user's crontab which is meant to pull records into a database table every 15 min:*/15 * * * * app_user cd /var/www/apps/my_app/current/ && rake thing:do_stuff RAILS_ENV=productionI can see that the cron daemon is running this task in the cron log, but the database table it's supposed to pull records into doesn't change. This task is working without error when I run it manually in the /var/www/apps/my_app/current directory, and pulls records into the table as I expect it to.I reset the PATH variable in the crontab to reflect using REE, thinking maybe the default path wouldn't jive with /opt/ruby-enterprise...How do I get this rake task to actually run with cron?
|
Rake Task from Crontab?
|
Runphp artisan listcommand in cmd and find your cron.Runphp artisan yourcron.You can readthis blog post on our websitefor more details about cron jobs.
|
I create a cron job on laravel 5.3 by editing app\Console\Kernel.php like this :<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use DB;
class Kernel extends ConsoleKernel
{
protected $commands = [
//
];
protected function schedule(Schedule $schedule)
{
$schedule->call(function () {
$id = 1;
DB::table('orders')
->where('id', $id)
->update(['status ' => 2, 'canceled_at' => date("Y-m-d H:i:s")]);
})->everyMinute();
}
protected function commands()
{
require base_path('routes/console.php');
}
}I tried to check on the table in the database, but it does not updateHow can I test my cron job?
|
How can I test my cron job in localhost windows? (laravel 5.3)
|
Seeperlfaq8.Here are three ways to add arbitrary directories to Perl's module search path.Set thePERL5LIBenvironment variable15 15 * * 1-5 PERL5LIB=/root/perl5/lib/perl5 /usr/local/bin/perl my_script.plUse the-Icommand line switch15 15 * * 1-5 /usr/local/bin/perl -I/root/perl5/lib/perl5 my_script.plUse thelibpragma inside your perl script#! /usr/local/bin/perl
# my_script.pl: the script that does my thing
use lib '/root/perl5/lib/perl5';
use Net::Finger;
...Also note that the environment of a cron job is much sparser than the environment of your command line, and in particular the cron environment's$PATHvariable might not be what you expect. If you're not specifying the full path to the Perl executable, verify what$PATHthe cron environment is using and make sure you are running the right version of perl.
|
I have perl programs that useNet::Fingerand have run successfully fromcron.dailyin Fedora 11.I just upgraded a server to Fedora 18 and these same perl programs no longer run from cron but run fine from command line when logged in as root.The error is:Can't locate Net/Finger.pm in @INC (@INC contains: /usr/local/lib64/perl5 /usr/local/share/perl5 /usr/lib64/perl5/vendor_perl /usr/share/perl5/vendor_perl /usr/lib64/perl5 /usr/share/perl5 .)The path to the module is/root/perl5/lib/perl5/Net/Finger.pmbut I can't figure out how to add the path without causing more errors.
Thanks in advance.
|
Perl can't find module when run from cron.daily
|
const dateToCron = (date) => {
const minutes = date.getMinutes();
const hours = date.getHours();
const days = date.getDate();
const months = date.getMonth() + 1;
const dayOfWeek = date.getDay();
return `${minutes} ${hours} ${days} ${months} ${dayOfWeek}`;
};
const dateText = '2017-05-09T01:30:00.123Z';
const date = new Date(dateText);
const cron = dateToCron(date);
console.log(cron); //30 5 9 5 2
|
A cronjob time syntax such as"* * * * * *"followedcron npmI want convert time from"2017-05-09T01:30:00.123Z"to cron job time format. Have library or method can implement it?
|
How to convert general time to cronjob time using nodejs?
|
It can be something like below:0 0 1 2,3,4,5,6,7,8,9,10,11,12 *
|
I would like to set up a cron task to run a script every first day of every month except 1st january. How can I do that?Could I try something like that: 0 0 1 2-12 * ?
|
Cron Job only specific months
|
The right way would be*/1 * * * * PYTHONPATH=/Library/Frameworks/Python.framework/Versions/Current/lib/python2.7/site-packages python /Users/JohnDoe/Desktop/createUpdate.pyPlease be aware of spaces in variable assignment. No semicolon and no need to export variables, since declaring them before the commands already makes them active for the command itself.
|
I'm very new to Unix and crontab. The only major issue I'm running into is pointing terminal to the python modules for the specific program I'm trying to run. From command line the program runs fine but won't from crontab.The first cronjob sends me an email saying that the cronjob is running. The second(createUpdate) runs a script I've built, set to run each minute.crontab -l returns:*/1 * * * * python /Users/JohnDoe/Desktop/emailalert.py
*/1 * * * * PYTHONPATH =/Library/Frameworks/Python.framework/Versions/Current/lib/python2.7/site-packages; export PYTHONPATH; python /Users/JohnDoe/Desktop/createUpdate.pyAm I structuring PYTHONPATH correctly?Should I break it out before the cron?Is 'export PYTHONPATH' necessary?EDITI forgot to add the error/bin/sh: PYTHONPATH: command not found
Traceback (most recent call last):
File "/Users/JohnDoe/Desktop/createUpdate.py", line 1, in <module>
import beatbox
ImportError: No module named beatbox
|
Crontab | Missing Python Module
|
Try to provide full path to iptables e.g.$ which iptables
/sbin/iptablesand than modify your script like that:\#!/bin/bash
#blah blah run some commands to get the IP
/sbin/iptables -A INPUT -s $p -j REJECT --reject-with icmp-host-prohibited
echo "BANNED $p FOR $COUNT ATTEMPTS" |wall
|
I have the following bash script to read logs and check for brute force then block violating IP using iptables.#!/bin/bash
#blah blah run some commands to get the IP
iptables -A INPUT -s $p -j REJECT --reject-with icmp-host-prohibited
echo "BANNED $p FOR $COUNT ATTEMPTS" |wallI did chmod 755. When I run the command from terminal it works fine. But when I setup a cronjob usingcrontab -eas root, it gets the IP and echos the "BANNED ..." message to the wall but nothing is added to the iptables list.PS. I tried both#!/bin/bashand#!/bin/shbut no luck.
|
Bash script commands not working in cron
|
The following is an expression that will execute every 15 minutes:0 0/15 * 1/1 * ? *So your expression would be:0 0/15 * 1/1 * ? * /home/yadda/something/etcYou may be interested in thecronmakerwebsite.
|
I am trying to setup a cron job to run the garbage collector every 15 minutes on my session directory to clean up sessions that are beyond the expiration limit I set in php.ini, in one of my subdirectory locations. I have never used cron jobs before so I was wondering if someone could help me.What I have so far is:15 * * * * /home/yadda/something/etc
|
Writing a cron expression to execute every 15 minutes
|
You should keep this file outside of public_html/usr/local/bin/php -f /home/mysite/script
// is secure from public access
|
Whats the best way to ensure that only CRON executes PHP scripts, and not someone else who stumbled upon your php scripts..I was thinking a Password Variable.... but is this a legal CRON command? :/usr/local/bin/php -f /home/mysite/public_html/dir/script?password=12345This way people cannot be able to execute the same commands when visiting the PHP script via HTTP (unless they know the password)Thanks.
|
PHP & cron: security issues
|
I'm using crontab as well to execute my Node JS project. I have to explicitly state the path of my.envfile like so:require('dotenv').config({ path: '/var/www/html/myproject/.env' });In python-dotenv, I believe it can be done similarly by using:# OR, explicitly providing path to '.env'
from pathlib import Path # Python 3.6+ only
env_path = Path('.') / '.env'
load_dotenv(dotenv_path=env_path)Source
|
I am running a python script from a python library which loads some environment variables from a.envfile in the root of the library using dotenv.This works from the command line, but when I try to run as a cronjob using the following:* * * * * source ./path_to_venv/activate; python ./path_to_script.pyI get a key error because it can't find the environment variable.Any ideas why this isn't working?Many thanks for any help!
|
Can't find dotenv environment variables from cron job
|
You are looking at the return value of the method, not the input. The input can only be a String in milliseconds, but the return value is a value compliant with Duration.
|
The@Scheduleddocumentation herestates that thefixedRateStringvalue can bethe delay in milliseconds as a String value, e.g. a placeholder or a java.time.Duration compliant value. Meaning I can either write@Scheduled(fixedRateString = "45s")OR@Scheduled(fixedRateString = "45000")And it should be the same. However when I try to run it I getEncountered invalid @Scheduled method 'updateWarmupInstances': Invalid fixedRateString value "45s" - cannot parse into longSo it this a mistake on Spring's part or am I doing something wrong
?
|
Spring scheduled fixedRateString as Duration
|
Cron command to run:/path/to/php -f /path/to/script.php >> /path/to/logfile.txt
|
Morning all,I have a php script which I have been testing, and seems to run fine when I call it from the command line.I now want to automate it via cron, how can I get the outputs I have put into the file as checkpoints into a log file?eg I have some simple echo commands in the script and I'd like the output to appear inside an existing log file (so that it get's automatically rotated etc)thanks,Greg
|
running a php script via cron, how can I log any output?
|
You have to escape percent signs with a backslash:0 0 * * * pg_dump DB_NAME > /path/to/dumps/`date +\%Y\%m\%d`.dmpFromman 5 crontab:The ‘‘sixth’’ field (the rest of the line) specifies the command to
be
run. The entire command portion of the line, up to a
newline or %
character, will be executed by /bin/sh or by the shell specified in
the
SHELL variable of the crontab file. Percent-signs (%) in the
command,
unless escaped with backslash (\), will be changed into newline
characters, and all data after the first % will be sent to the command
as
standard input. There is no way to split a single command line
onto
multiple lines, like the shell’s trailing "\".
|
This question already has answers here:How is % (percent sign) special in crontab?(2 answers)Closed5 years ago.I have acrontabthat looks like0 0 * * * pg_dump DB_NAME > /path/to/dumps/`date +%Y%m%d`.dmpwhich works fine when I run it manually, but not whencronruns it. After digging through the logs, I seeDec 12 00:00:01 localhost crond[17638]: (postgres) CMD (pg_dump DB_NAME > /path/to/dumps/`date +)It looks like a problem with percent signs, but themanpage doesn't even contain the percent character at all, so I thought they were alright.
|
Is there a special restriction on commands executed by cron? [duplicate]
|
It's not quite clear what do you mean under "executing http address"But you can try this settingSince Plesk12.5there are task options:In Plesk 12 and below:
|
I'm a total newbie with Plesk, and I'm wondering how to set up a cron task for executing http address, which is updating profiles. I have my link of course, and I want to run this link every 15 minutes, 24 hours a day, non-stop.I'd be very glad if you guys could help me with that.Here's my cron task configuration for root:What should I fill in minute, hour, day? And how about command?Thanks for helping me,
Mike
|
How to set up a cron task in Plesk every 15 minutes?
|
FACT: you can run as many cron jobs from a single crontab file as you wish.FACT: you can also rundifferentjobs asdifferentusers, each with their own crontab file.SUGGESTION:1) Just debug what's wrong with your second job.2) It could be path, it could be permissions; it's more than likely environment (the environment for "cron" can be different from the environment for the same user from a command line).PS:Try this, too:How to simulate the environment cron executes a script with?Debugging crontab jobs
|
I wanted to implement two cronjobs with different execution time. One cron job is for sending emails and second cron job for validating my application subscriptions.I write one crontab file and write to two cronjob as follows:2 * * * * path to mailCronjob mail.php
20 * * * * path to check my application's subscriptions sub.phpThe problem is first cronjob is working fine. Mail will delivers fine, but the second cronjob
is not working. I tried to run second job manually, its also working fine.I am using command to set cronjob as:crontab crontab_filewhen I give commandcrontab -lit also shows both cronjob in command line.I wanted to ask, am I missing something here, or what should I do to run those cronjobs.
|
Multiple Cron jobs in one crontab file
|
The main.py script calls some methods from other modules under python_prj, does that matter?Yes, it does. All modules need to be findable at run time. You can accomplish this in several ways, but the most appropriate might be to set the PYTHONPATH variable in your crontab.You might also want to set the MAILTO variable in crontab so you get emails with any tracebacks.[update] here is the top of my crontab:www:~# crontab -l
DJANGO_SETTINGS_MODULE=djangocron.settings
PATH=...
PYTHONPATH=/home/django
MAILTO="[email protected]"
...
# m h dom mon dow command
10-50/10 * * * * /home/django/cleanup_actions.py
...(running cleanup actions every 10 minutes, except at the top of the hour).
|
crontabfails to execute a Python script. The command line I am using to run the Python script is ok.These are solutions I had tried:add#!/usr/bin/env pythonat the top of themain.pyaddPATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/binat the top ofcrontabchmod 777to themain.pyfileservice cron restartmy crontab is:PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin
*/1 * * * * python /home/python_prj/main.pyand the log in /var/log/syslog is:Nov 6 07:08:01 localhost CRON[28146]: (root) CMD (python /home/python_prj/main.py)and nothing else.Themain.pyscript calls some methods from other modules underpython_prj, does that matter?Anyone can help me?
|
Crontab fails to execute Python script
|
I don’t think ranges can wrap around like that. Specify the hour as0-9,18-23instead.
|
I just want to set a crontab using that I want to make a program run at every 15 minutes
from 18:00 to 09:00I have given this statement and waited but I don't think it is working*/15 18-9 * * 1-6 Program_nameAny suggestion would be greatly appreciated
|
Crontab sets 18:00 to 09:00
|
Per thekubernetes Cronjob docs, there does not seem to be a way to cleanly resolve this. Setting the.spec.startingDeadlineSecondsvalue to a large number will re-scheduleallmissed occurrences that fall within the increased window.My solution was just tokubectl delete cronjob x-y-zand recreate it, which worked as desired.
|
I have a cluster that includes a Cronjob scheduled to run every 5 minutes.We recently experienced an issue that incurred downtime and required manual recovery of the cluster. Although now healthy again, this particular cronjob is failing to run with the following error:Cannot determine if job needs to be started: Too many missed start time (> 100). Set or decrease .spec.startingDeadlineSeconds or check clock skew.I understand that the Cronjob has 'missed' a number of scheduled jobs while the cluster was down, and this has past a threshold at which no further jobs will be scheduled.How can I reset the number of missed start times and have these jobs scheduled again (without schedulingallthe missed jobs to suddenly run?)
|
Kubernetes Cronjob: Reset missed start times after cluster recovery
|
Followingthistutorial I believe you just have to do:const cron = require("node-cron");
cron.schedule("* * 1 * *", function() {
// Do something
});where:
|
I am using node-cron package for scheduling node-cron jobs. I want to schedule an node-cron job which will run every new month.
for example:
My node-cron job should run at1 September 2020after that it should run at1 October 2020and and so on..!
Please help me out for the above issue.
Thanks in advance.
|
How to schedule node-cron job every new month?
|
I just change the path on dotenv config and it worked for meconst dotenv = require('dotenv');
dotenv.config({ path: __dirname + '/../.env' });
|
I've currently got a cron job setup where it runs a Node.js script. The Node.js script uses thedotenvpackage to read a.envfile that has some API keys.When I run the Node.js script from the command line, the variables are read correctly from the.envfile and works with my Node.js script.But when cron runs the Node.js script, the variables that I'm trying to set return undefined.00 05 * * * /home/michaellee/.nvm/versions/node/v6.10.0/bin/node /home/michaellee/index.js >> /home/michaellee/output.logThe.envfile resides in the same level as theindex.jsfile.The cron job is set usingcrontab -efrom the usermichaellee, the same user that has the files on Ubuntu.
|
How do you get cron job running Node.js script to read variables from .env file?
|
If the cronjob runs every 5 minutes, try this configuration:Generate Schedules Every 5(enter here the cronjob execution time, in this case 5 minutes)Schedule Ahead for 125(based on cronjob execution time plus the maximum time one job needs. For example: sitemap generation takes 120 minutes, then enter 120 minutes + 5 = 125 minutes)Missed if Not Run Within 180(runtime of the longest process, for example: an import takes 120 minutes, then enter 120 minutes + 60 minutes - because sometimes there is a difference between mysql and server time)History Cleanup Every 10(minimum cronjob execution time = 5 * 2 = 10 minutes in this case)Success History Lifetime 1440(duration of cronjob storage, to proof if everything works fine. 1440 = 24 hours)Failure History Lifetime 1440(duration of cronjob storage, to proof if there is an error. 1440 = 24 hours)And last but not least, install AOE-Scheduler for a visual inspection of your cronjobs.http://www.magentocommerce.com/magento-connect/aoe-scheduler.html
|
I created some modules to be executed by magento cron but i get always the error.
The numbers:Cron.php gets executed every 5 minutessystem/cron/schedule_generate_every = 15system/cron/schedule_ahead_for = 30system/cron/schedule_lifetime = 15The module cronjobs should be executed every 5 minutes.
They are added correct to cron_schedule to be executed i.e. at 2014-01-16 16:40:00, 2014-01-16 16:45:00, 2014-01-16 16:50:00 ...
But on execution in 16:50 i get lots of errors. exception 'Mage_Core_Exception' with message 'Too late for the schedule.' also for jobs in the future.Perhaps: our local time is 17:50, server time 16:50. But i can't remember we had this issue before on other cronjobs.
|
Magento 1.7 - Cron.php: too late for the schedule
|
Consider these tipsUse Rscript (or littler) rather thanR CMD BATCHMake sure the cron job is running as youMake sure the script runs by itselfTest it a few times in verbose modeMy box is running the somewhat visibleCRANberriesvia a cronjob calling an R script
(which I execute vialittlerbut Rscript
should work just as well). For this, the entry in/etc/crontabon my Ubuntu server is# every few hours, run cranberries
16 */3 * * * edd cd /home/edd/cranberries && ./cranberries.rso every sixteen minutes past every third hour, a shell command is being run with my id. It changes into the working directory, and call the R script (which has executable modes etc).Looking at this, I could actually just run the script and havesetwd()command in it....
|
I am trying to schedule my R script using cron, but it is not working. It seems R can not find packages in cron. Anyone can help me? Thanks.The following is my bash script# source my profile
. /home/winie/.profile
# script.R will load packages
R CMD BATCH /home/script.R
|
Schedule R script using cron
|
Curl is your friend. In your case, you would have something like this:0 8 * * * curl -X POST -d '{"message":"content"}' apidomain.com/endpoint/In my example, I specify POST even though curl will default to a POST when you specify data (with the -d option). I've included it in case your API expects a different HTTP method like GET or PUT.The curl manpage will help:https://linux.die.net/man/1/curlAnd see this answer for some help with JSON and curl:https://stackoverflow.com/a/7173011/1876622
|
I'm a newbie, I have a project which needs to send daily reminders to users. I see that you can do this using cron jobs. However, I need to call the API which has the daily reminder. This API is an external one. How do I do that?UPATE:I need to invoke the API and then get the response and send email to users daily.
|
How to call API in cron?
|
Here you are creating 2 CronJobs that will both run. In order to "change" the period, you have to first stop the first Cronjob and then create a new one.For example (untested code)var job;
var period = 1;
var CronJob = require('cron').CronJob;
function createCron(job, newPeriod) {
if (job) {
job.stop();
}
job = new CronJob('*/' + newPeriod + ' * * * * *', function () {
console.log("some task");
}, null, true, "Indian/Mauritius");
}
createCron(job, 1);
setTimeout(function() {
period = period * 2;
createCron(job, period);
}, 60000);
|
I need to do some task periodically in my nodejs app. If it was fixed period then it is working fine. But in my case the period should change dynamically. below is my code which was not working as I expected. here cronjob is not updating it's period when I changed the period.var period = 1;
var CronJob = require('cron').CronJob;
new CronJob('*/' + period + ' * * * * *', function () {
console.log("some task");
}, null, true, "Indian/Mauritius");
new CronJob('*/5 * * * * *', function () {
period = period * 2;
console.log("updating cronjob period");
}, null, true, "Indian/Mauritius");
|
Dynamically update nodejs cronjob period
|
Will theCronTriggerFactoryBean.setCronExpression()method work?
|
I'm a bit stuck migrating to latest quartz 2.2 and spring 4.1... Here's a cron trigger, I omit the job and other fluff for clarity:...
<bean id="timeSyncTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="timeSyncJob"/>
<property name="startDelay" value="10000"/>
<property name="cronExpression" value="0 0 1 * * ? *"/>
</bean>
...Now, I need to change itscronExpressionat run time, and it's not as simple as I thought. I can't reference the bean and change the property because its a factory givingCronTriggerinterface which in turn doesn't havesetCronExpressionmethod any longer, it has become immutable. Before I could simply fish out a trigger from the context and set its new cron expression. It worked very well for many years, until the upgrade become unavoidable.So, how do we accomplish this simple task today? Totally lost in documentations and versions.. Thanks in advance!
|
How to change cron expression in CronTrigger (quartz 2.2, spring 4.1)
|
You can for example use:*/10 11-13,17-19 * * * /your/script # every 10 min 11.00 to 13.00, 17.00 to 19.00
0 0-10,14-16,20-23 * * * /your/script # every 1 hour 00.00 to 10.00, 14.00 to 16.00, 20.00 to 23.00*/10 11-13,17-19 * * *means: every 10 minutes on the hours 11 to 13 and 17 to 19. That is, to happen between, 11.00 and 13.59 and 17.00 and 19.59.0 0-10,14-16,20-23 * * *means: every minute0on the hours 0 to 10, 14 to 16 and 20 to 23. That is, to happen at exactly hours 0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 14, 15, 16, 20, 21, 22 and 23 (all but 11, 12, 13, 17, 18 and 19).Remember the format is like this:+---------------- 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
|
Is it possible to run a cron job for different frequencies throughout the day? Or to achieve the same effect, is it possible to have the cron job run on a regular frequency but only during certain hours of the day?ExampleI would like to run my script 6/hour between 11am - 2pm, and 6/hour between 5pm - 8pm. Otherwise, I would like the script to run 1/hour.
|
Running Cron Job at different frequencies throughout day
|
I wouldn't use cron for this. I would use that bash script (use an absolute path, unless you want it to be portable andknowthat the directory structure will be preserved).Instead, I would justsleep 5, just like you did (only 5 seconds instead of 1).As far as starting it with your system, that depends on the system. On (some) Linux distros, there's a file called/etc/rc.localin which you can add scripts to run when the system starts. Well... I shouldn't be so general, the distros that I have used have this. If you're running Ubuntu, there is no longer an inittab, they use upstart, btw.So if you have an endless loop and an entry in/etc/rc.local, then you should be golden for it to run endlessly (or until it encounters a problem and exits).
|
I want to create cron job that runs a script every 5 seconds. Seeing that cron jobs only allows increments of minutes 0-59 and so on.I thought to create another script that calls my original script written below.#!/bin/bash
while true
do
# script in the same directory as this script. is this correct?
bash makemehappy.sh
sleep 1
doneI now, need to know how to run this script every time i boot my computer and for it to start itself if it isn't running for some reason.I am also aware that running this script every minute wouldn't be a good thing. :)if there is an easier way to run a script every 5 seconds please advise.Please and thank you.
|
Cron jobs -- to run every 5 seconds
|
If you get enough hits this will work...Store a last update time somewhere(file, db, etc...). In a file that gets enough hits add a code that checks if the last update time was more xx minutes ago. If it was then run the script.
|
I'm pretty sure I've seen this done in a php script once, although I cant find the script. It was some script that would automatically check for updates to that script, and then replace itself if there was an update.I don't actually need all that, I just want to be able to make my PHP script automatically run every 30 minutes to an hour, but I'd like to do it without cronjobs, if its possible.Any suggestions? Or is it even possible?EDIT:After reading through apossible duplicatethat RC linked to, I'd like to clarify.I'd like to do this completely without using resources outside of the PHP script. AKA no outside cronjobs that send a GET request. I'd also like to do it without keeping the script running constantly and sleeping for 30 minutes
|
Is it possible to make a PHP script run itself every hour or so without the use of a cronjob?
|
There are many answers, however there is not even one correct at the time of writing.PHPtime()function doesn't return the system time, like most folks believe, but it return the PHP localtime, normally set withdate.timezonein php.ini, or set withdate_default_timezone_set()within a script.For instance in one of my servers, PHP time was set toEurope/Romeand system time toUTC. I had a difference of one hour between system time and PHP time.I'm going to give you a solution that works for Linux, I don't know for Windows. In Linux the system timezone is set in/etc/timezone. Now, this is normally outside my allowedopen_basedirsetting, but you can add:/etc/timezoneto your list to be able to read the file.Then, on top of the scripts, that want to get the system time, you can call a library function that sets the script timezone to the system timezone. I suppose that this function is part of a class, so I use static:static function setSystemTz() {
$systemTz = trim(file_get_contents("/etc/timezone"));
if ($systemTz == 'Etc/UTC') $systemTz = 'UTC';
date_default_timezone_set($systemTz);
}To make the matter worse in PHP 5.3.3 'Etc/UTC' is not recognized, while 'UTC' is, so I had to add an if to fix that.Now you can happily calltime()and it will really give you the system time. I've tested it, because I needed it for myself, that's why I found this question now.
|
I'm writing a PHP system and I need to get the system time. Not the GMT time or the time specific to a timezone, but the same system time that is used by the CRON system. I have a CRON job that runs every day at midnight and I want to show on a webpage how long will it take before it runs again.For example:
Right now it is 6pm on my system clock. I run the code:$timeLeftUntilMidnight = date("H:i", strtotime("tomorrow") - strtotime("now"));The result, however, is "3:00" instead of "6:00". If I rundate("H:i", strtotime("tomorrow"));It returns 0:00, which is correct. But if I rundate("H:i", strtotime("now"));It returns 21:00, even though the correct should be 18:00.Thanks.
|
How do I get the local system time in PHP?
|
with the kohana framework you can pass the "uri" as a command line parameter:/path/to/index.php controller/method/paramyou might want to try that, you will definitely need a controller but you dont need to use wget or curl
|
I need to call a Kohana helper (or any php MVC framework) from a Cron job.How can I do this?The server is Linux, so, I can only think of two possible solutions:1- Open an URL from the cron job, which hits a controller and does what it has to do.2- Call a Kohana controller without passing through the web server, but with the PHP CLI. (is that even possible? I don't think so, it might need the web server environment to work)Know a solution?
Thanks
|
Call a Kohana helper from cron (or any URL)
|
If you have a separate version of python installed for 2.7 you can look for it withwhereis pythonI have CentOS 6 which comes with 2.6 by default, so this command returns:python2: /usr/bin/python2.6 /usr/bin/python2.6-config /usr/bin/python2 /usr/lib/python2.6 /usr/lib64/python2.6 /usr/local/bin/python2.7-config /usr/local/bin/python2.7 /usr/local/lib/python2.7 /usr/include/python2.6Of these/usr/local/bin/python2.7is the one I'm interested in, so when I put a job in crontab, I choose it explicitly:30 00 * * * /usr/local/bin/python2.7 /home/mike/job.py
|
crontab is using version 2.6 to run a script that requires 2.7 to run. How do I set the default version of Python to be 2.7 permanently?
running ./file.py works fine, its just when its run through crontabSHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/
# For details see man 4 crontabs
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
*,30 * * * * root /root/file.py >>/tmp/log.txt 2>&1edit
issue resolvedSHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin/python
MAILTO=root
HOME=/
# For details see man 4 crontabs
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
*,30 * * * * root /usr/local/bin/python2.7 /root/file.py >>/tmp/log.txt 2>&1
|
Crontab using incorrect version of Python to run script
|
Here are 4 libs you could take a look at:https://github.com/erlware/erlcronhttps://github.com/b3rnie/crontabhttps://github.com/jeraymond/leader_cronhttps://github.com/zhongwencool/ecron
|
I need to provide a way to perform actions at specific date/time repeatedly. Basically it should work likeCronand I'm thinking of the way of managing execution times.One solution could be to run a loop in each job/process and constantly check (every minute or second) whether current time is the time we are waiting for.Another solution could be to work withtimersby waiting until the next execution. We calculate the difference between now and the next execution time, and supply that delay to the timer. But since the execution times should be manageable, we would need to have a way to interrupt that timer and create a new one, or we could simply kill that process and create a fresh one.Does anyone have any thoughts on how it should be done properly, or are they any libraries for accomplishing this particular scenario?
|
Cron implementation in Erlang
|
Did you try this :0 0/5 0,2-23 * * ?
|
My need is clear in the title. Any help would be appreciated.
|
Cron expression for each 5 minutes except hours between 01:00 and 02:00?
|
You should try to capture stderr in addition to stdout so that you can find out exactly why the program is failing (assuming it does indeed print some errors for you)cmd = ['/path/to/casperjs', '/path/to/doSomething.js', 'args']
response = subprocess.check_output(cmd,
shell=True,
stderr=subprocess.STDOUT)
|
I have a Python script that manages a series ofCasperJStasks and processes the result. It runs well from the command line, but when I run the script in cron, I get the error:CalledProcessError: Command '['/path/to/casperjs', '/path/to/doSomething.js', 'args']' returned non-zero exit status 1In Python, I call CasperJS:response = subprocess.check_output(['/path/to/casperjs', '/path/to/doSomething.js', 'args'], shell=True)I have triedshell=FalseandPopenas well, but I get the same result. I also tried making the entire command a string (instead of list), but that didn't help either.Running'/path/to/casperjs /path/to/doSomething.js args'returns exit code 0 when run in the shell.I have also addedPATH=/usr/bin:/bin:/sbin:/usr/local/binto my crontab to no avail. (As suggested inthis question.)Any ideas why I'm only getting this error in cron? Thanks!!EDIT:In accordance with the answer below, settingshell=Falseandstderr=subprocess.STDOUTmade everything work...
|
Python Subprocess returns non-zero exit status only in cron
|
After doing some research on google I find its answer and it is very easy.Just include a particular hour or range (between 0,23) in hour column i.e 2nd columns* 22-23,23,0-9 * * *This will run a con job for every minute starting from10:00 PMto09:00 AM
|
I am setting aCron Jobto run every minute between10 PM to 11 PMas below and its working fine.*/1 22-23 * * *But when I want to set up it between11PM to 12AM (Midnight)as below*/1 23-00 * * *Its showing error as low limit value no. (i.e 23) should be less than higher limit (i.e 00).
I have searched on google (or saystackoverflow:D) but have not find any way to run acron jobbetween11PM-12AM.
|
How to set cron job to run every minute between 11 PM to 12AM Midnight
|
Incrontab -e, make this your first line:PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/binThenwgetshould work without specifying the full path.You can also just specify the full path towget(which wgetto find it):/usr/bin/wget --output-document="/Users/proudowner/Desktop/tfgo/bp.json" http://backpack.tf/api/IGetMarketPrices/v1/?key=55085a94ba8d88d1538b4576
|
So I'm trying to run awgetcommand using crontab every 5 minutes. My problem that I have is it's just not running. I didcrontab -lto see what was running, the command is there.the command is:wget --output-document="/Users/proudowner/Desktop/tfgo/bp.json" http://backpack.tf/api/IGetMarketPrices/v1/?key=<key>And the error log says:/bin/sh: wget: command not foundThe command also runs fine withoutcrontab.
|
crontab not running wget
|
+50date -Iminutescould be the way to go, which uses ISO 8601 format.
TheWiki pagehas some info.
|
The following works:/usr/bin/mysqldump -u[username] -p[password] --all-databases --single-transaction > /home/[domain]/public_html/backups/full_backup_`date -I`.sqlIt results in "full_backup_2012-11-04.sql"The cron job is going every minute but the filename is only for once a day... I wanted to include the hour and minute in the filename as well.... (in the end the cron job might be run every hour or so)So date -I works... other typical options for date don't seem to work... is there any documentation that says -I is valid? If so that documentation might also have other options that work.
|
Adding the time to mysqldump cron job?
|
Starting from a list of cron expressions (e.g. read from database) you could iterate over the list and start a quartz consumer actor for each element. Here's an example:import akka.actor.Actor
import akka.actor.Actor._
import akka.camel.CamelServiceManager._
import akka.camel.Consumer
object CronExample {
def main(args: Array[String]) {
val cronExpressions: List[String] = ... // cron expressions read from database
startCamelService
cronExpressions foreach { cronExpression =>
val timerName: String = ... // app-specific timer name for cronExpression
actorOf(new Scheduler(timerName, cronExpression)).start
}
}
class Scheduler(timerName: String, cronExpression: String) extends Actor with Consumer {
def endpointUri = "quartz://%s?cron=%s" format (timerName, cronExpression)
protected def receive = {
case msg => ... // react on timer event
}
}
}
|
I have a Db of Quartz CronTriggers. I want to port this entire system to an Akka based backend I am architecting currently. I was looking at and thinking about ways this can be done.For instance, CustomRouteBuilders and other similar stuff. I tried the excellent Quartz-Camel-Akka integration example by Giovani and was quite impressed with it. Now, I have multiple cron triggers in my system with different and user created cron expressions.How can I program a system of Camel Consumer Actors with such user dependent endpointUri's? Was thinking of many options but could not figure out anything yet.Please help me in this endeavor. I am also open to other ideas beyond Quartz and Camel. I want to stick to Akka based backend platform. My system consists of user defined jobs that fire at user defined cron formable timings.
|
Quartz CronTriggers in Akka Actors using or not using Camel?
|
the simple answer is no. from thedocsit is clearly stated that cron jobs use HTTP GET. the best thing is to change your method to GET and restrict direct access to the url in your app.yaml.
like this:handlers:
- url: /report/weekly
script: reports.app
login: admin
|
Is it possible to make a cron request to a URL via Google App Engine usingmethod=post. I could not find anything in the documentation allowing different methods other thanget.https://developers.google.com/appengine/docs/python/config/cron#Python_app_yaml_Cron_support_in_the_development_server
|
Google App Engine Cron Requests Using POST
|
Why do you want to do this?If you are experiencing a specific problem with Apache.It Will definitely be more beneficial for you to have a look into the access/error logs, and make adjustments accordingly.Give us some more information and we can look into your logs and give you a more appropriate solution.None the less heres the cron to restart apache.0 */3 * * */ root/restart_apache > /dev/null 2>&1/etc/init.d/httpd restart
|
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed11 years ago.Improve this questionMy server is currently suffering from some problems due to visitors lag and i think the best solution for it, is to restart apache every 2/3 hours or soHow can i do this through cronjob ?
|
Crontab - Restart apache every 3 hours [closed]
|
I did a little research, and it basically comes down to 3 answers that I can find:Quick answer: You can't.Complex answer 1: You could manually put in an entry for every other Sunday on a separate line, but this will run into problems when the year changes0 0 29 4 *
0 0 13 5 *
0 0 27 5 *
0 0 10 6 *
...Complex answer 2: Create a cron entry that runs every Sunday, and then use something in your build steps that manually checks (toggles) to solve the "every other" part of the problem. (If you need to do the test before the SCM step, the pre-scm-buildstep plugin might help.)
|
I wanted to schedule fortnightly job on jenkin . It should run every other Monday . I am not able to figure out the cron expression
|
Schedule Fortnightly jobs on jenkins
|
Regarding how to import a dump file, simply put amysql -u user -ppassword databasename < /path/to/dump.sqlinto the cron job.More details:How do I restore a MySQL .dump file?
|
I'm new to cron jobs and I need to restore a database (mysql) every 30 minutes. Is there a cron job command that can restore a database from a .sql file that's been gzipped?Or do I need to create a php script to do this and create a cron job to call this script every thirty minutes?Also, and this is a separate question but still related to cron jobs, I'm using a cron job to backup a different database once a day, gzip it and put it in a folder above the root. Is there a way to (automatically) delete anything older than a month? Or, at least, keep the most recent 20 backups and delete the rest?There's not a lot of good tutorial out there on this subject other that random forum posts. Any help is appreciated.
|
I need to restore a database (mysql) every 30 minutes using a cron job
|
Someone on serverfault answered a similar question -Crontab maximum command length999 characters.Just create a bash script and run it instead of having the entire command in crontab.
|
I want to execute a command every minute (SSH). The command is a cURL bash, the length is 1625. When I put in the command in the crontabs and save:"/tmp/crontab.ijKPl1/crontab":51: command too long
errors in crontab file, can't install.
Do you want to retry the same edit? (y/n)
|
Maximum length for cron job
|
The best way to handle this in a generic way is to have a shared database that you write a "lock" entry to. As in, let's say all tasks wrote a DB entry such as{instanceId: "a", taskId: "myTask", timestamp: "2021-12-22:10:35"}.All tasks would submit the same thing except with their own instanceId. You then have an unique index on 'timestamp' so that only 1 gets accepted.Then they all do a query and see if their node was the one that was accepted to do the cron.You could do the same thing but also add a "random" field that generates a random number and the task with the lowest number wins.
|
I'm building in a CRON like module into my service (usingnode-schedule) that will get required into each instance of my multi-core setup and I'm wondering since they are all running their own threads and they are all scheduled to run at the same time, will they get called for every single thread or just once because they're all loading the same module.If they do get called multiple times, then what is the best way to make sure the desired actions only get called once?
|
CRON + Nodejs + multiple cores => behaviour?
|
You can do it with 3 cron strings:0 12-59/6 9 * * *
0 /6 10-16 * * *
0 0-37/6 17 * * *Give them all the same task to run.
|
For Quartz Cron, is it possible at all to specify a cronexpression that corresponds to:Run every 6 minutes, starting from 9:12 AM until 5:37 PM.I attempted to write the cronexpression0 12-37/6 9-17 ? * *but this does only runs once an hour. I alsounderstandthat the cronexpression0 /6 9-17 ? * *corresponds toRun every 6 minutes between the hours of 9 AM and 5 PM.But is there any way to constrain the starting and ending minutes on that cronexpression? More generally, can I specify an arbitrary start and end time with the job in question running everynintervals of time?
|
Specify arbitrary start and end times for cron job
|
In your DirectAdmin panel go to 'cronjobs' section, I assume you already configured time interval for your cronjob, so you just need to adjust 'command' option, so try:First option:/usr/bin/php -f /home/your_user/public_html/your_script.phpThis way you will call php script with php interpreter.Second option:lynx -source http://yourdomain.com/your_script.phpThis way you will execute text based web browser lynx and open desired url so that php script can be run. Lynx is installed by default on most linux servers.Also I believe that there is a option in DirecAdmin cronjobs section called 'Prevent email' check that so that you don't receive emails.
|
I've got a PHP script (just a simple script) and I'm trying to get it to run as a cronjob. Every time it executes the PHP script, I receive a mail with the PHP script itself.How can I resolve this? I've searched on Google a lot but I can't find anything that works.
|
Why won't cron execute my PHP script correctly?
|
skip the shell script and use* * * * * /usr/bin/nice -n 10 /path/php -q /path/script.phpnice and\or php path may or may not be required
|
I have this php script that I need to run on shared webhosting.
I have created a cron job that executes an sh script. The command for the cron was:/bin/sh /home/user/script.shSo I'm assuming it is Bourne Shell (or something compatible). The script itself was:#!/bin/sh
cd /home/user/public_html/folder/
#updating DB
php -q ./run_interactive_job.php batch_control_files/updateDB
echo Updated DB resultsMy question is:Can I addNicepriorities to the php command ? Or do I need to add it to the script at the cron command. Which one is more likely to work ?nice 10 php -q ./run_interactive_job.php batch_control_files/updateDBWould that be successful at running at a lower priority.PS:Basically, this script has overloaded the server before when I ran it through the browser and it affected apache on that server resulting in my hosts blocking the file. I have repeatedly asked them unblock to test it with different parameters. And Now I'm trying to run it through cron at a lower priority in the hopes that it won't affect apache. But I don't want it to create issues again, hence I'm trying to useNICEIf anyone has any other suggestion that would offer a similar solution of running the php script without affecting apache or the webserver, that'sgreat too.
|
Nice command in .sh script for Cron Jobs
|
This is something that comes up quite often, see e.g.this document,this forum threadorthis stackoverflow question.The answer is basically no. What I would do in your situtation is to run the job every Tuesday and have the first build step check whether to actually run by e.g. checking whether a file exists and only running if it doesn't. If it exists, it would be deleted so that the job can run the next time this check occurs. You would of course also have to check whether it's Tuesday.
|
I want to schedule Jenkins to run a certain job at 8:00 am every Monday, Wednesday Thursday and Friday and 8:00 amevery otherTuesday.Right now, the best I can think of is:# 8am every Monday, Wednesday, Thursday, and Friday:
0 8 * * 1,3-5
# 8am on specific desired Tuesdays, one line per month:
0 8 13,27 3 2
0 8 10,24 4 2
0 8 8,22 5 2
0 8 5,19 6 2
0 8 3,17,31 7 2
0 8 14,28 8 2
0 8 11,25 9 2
0 8 9,23 10 2
0 8 6,20 11 2
0 8 4,18 12 2which is is fine (if ugly) for the remainder of 2012, but it almost certainly won't do what I want in 2013.Is there a more concise way to do this, or one that's year-independant?
|
Can I set Jenkins' "Build periodically" to build every other Tuesday starting March 13?
|
Found the problem, cron processes starts with very basic env variables. Some variables that were necessary for the code were missing, what made the problem.
|
I have a Node.JS automation which uses Puppeteer and loads some URLs as part of the process.
My code is pretty basic and uses just the very basic functions as documented in the package documentation.The automation is scheduled to run with crontab every 15 minutes, but for some reasons run after run I am facing aTimeoutError: Navigation Timeout Exceeded: 30000ms exceededError and the page is not loaded successfully.
When I run the exact same code manually everything works well and the page load pretty fast.Can someone think of anything that can the reason for this strange behavior?Thanks
|
Puppeteer "TimeoutError: Navigation Timeout Exceeded: 30000ms exceeded" when running from Crontab
|
The following cron job will runRscript scriptSecos.Rfrom the path/home/script2, once a day, at 0:00 (midnight).0 0 * * * cd /home/script2; Rscript scriptSecos.R >/dev/null 2>&1If you want to save the output of the script to a file, change>/dev/nullwith>/path/to/file.You can copy and paste this cronjob in your crontab file (You can open the file by using commandcrontab –e)
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Closed8 years ago.This question does not appear to be abouta specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic onanother Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.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.Improve this questionI am trying to schedule a cronjob to execute an R Script in a linux server. I have achieved to type the commands in the server manually and it works. To do so i have to type the following commands:root@debian:~# cd /home/script2root@debian:/home/script2# Rscript scriptSecos.RHow can i specify a cronjob that will execute the previous commands, once a day?Thank you.
|
How to schedule an R Script Cronjob in a linux server? [closed]
|
This can be done through following shell script and a frequent cron job.cpu_monitor.shCPU=$(sar 1 5 | grep "Average" | sed 's/^.* //')
if [ $CPU -lt 20 ]
then
cat mail_content.html | /usr/lib/sendmail -t
else
echo "Normal"
fimail_content.htmlFrom:[email protected]To:[email protected]Subject: Subject of the mail
Mime-Version: 1.0
Content-Type: text/html
<h1>CPU usage increased heigh</h1>Here the script will take the CPU ideal percentage for each 1 seconds. And 5 samples will be taken. Then average of that ideal percentage will be passed to variableCPU. When the ideal goes below the 20% mail will be send out.We can setup the cron with 5 minute duration.*/5 * * * * cd /full/path/to/script/; ./cpu_monitor.sh;
|
In a Linux / Unix server when the CPU usage go above a threshold value it need to send out a email alert. Propose a way to do it through cron tab and shell scripting.
|
Send alert email if CPU usage is continuously higher than a certain amount
|
You can redirect the output tocat(assuming the script testssys.stdout's file descriptor'satty-ness).python myscript.py | cata.pyimport sys
print sys.stdout.isatty()to test:> python a.py
True
> python a.py | cat
False
|
I am writing a bash script that will be called from cron.The bash script runs a python command that is sensing when it's in a terminal by usingpythons os.isatty functionand outputs different things depending on if it's run manually or via a cron. This is making debugging very hard and I would like to make it so that it always assumes it ISN'T in a TTY.I would like to be able to add something to the bash script to fool the python script that it is not being run in a terminal and so always output the same thing.To confirm, I have control of the bash script but don't want to edit the python as this is a packaged app.Any ideas?I hope that made sense.Thank you very much in advance.
|
Fool python's os.isatty from a bash script
|
You haven't posted your crontab, but I suspect you are not using the correct path to Python 3.6. Your cron error email says the PATH cron is using is /usr/bin and /bin. Your cron command calls just "python". So cron will use its PATH to try and resolve "python".Is an executable or link to Python 3.6 available in either of those locations?What do you see if you run:$ /usr/bin/pythonor$ /bin/pythonfrom your own login? I'm guessing that one, the other, or both would start a different version of Python (i.e. Python 2.x.x)Find out exactly where python3 is installed. Example (your results may be different):$ which python3
/usr/local/bin/python3In crontab, use this same absolute path when you specify the python executable and the path to your script (also using an absolute path).crontab0 0 * * * /usr/local/bin/python3 /Users/user/downloads/random/milbtrans.commandI suggest you try it like this first without the PYTHONPATH.You could also be more elegant and manage environment variables for the cron execution context (i.e. exporting a correct PATH environment variable via the crontab itself or a "wrapper" shell script) which would also solve the problem, but based on what you've shared here I believe this is the simplest way to address your current issue.
|
For some reason, Cron won't process this and keeps telling me that pandas is not installed (it is whenever I normally run my code)I'm getting this mail:Subject: Cron <user@Justins-MBP-4> PYTHONPATH=/Users/user/Library/Python/3.6/lib/python/site-packages python ~/downloads/random/milbtrans.command
X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <PATH=/usr/bin:/bin>
X-Cron-Env: <LOGNAME=user>
X-Cron-Env: <USER=user>
X-Cron-Env: <HOME=/Users/user>
Date: Tue, 8 May 2018 11:18:01 -0400 (EDT)
Traceback (most recent call last):
File "/Users/user/downloads/random/milbtrans.command", line 2, in <module>
import requests, csv, pandas, openpyxl, datetime, time
ImportError: No module named pandasChanged Pandas to be fixed but now getting this error:Traceback (most recent call last):
File "/Users/user/downloads/random/milbtrans.command", line 2, in <module>
import requests, csv, sys, pandas, openpyxl, datetime, time
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/__init__.py", line 19, in <module>
"Missing required dependencies {0}".format(missing_dependencies))
ImportError: Missing required dependencies ['numpy']Any help is appreciated.
|
Crontab No module named Pandas
|
This in your service file should do something very close to your requirements:[Service]
Restart=always
[Unit]
StartLimitAction=reboot
StartLimitIntervalSec=60
StartLimitBurst=5It will restart the service if it stops, except if there are more than 5 restarts in 60 seconds: in that case it will reboot.You may also want to look atWatchdogSecvalue, but this software watchdog functionality requires support from the service itself (very easy to add though, see the documentation for WatchDogSec).
|
I need to have a systemd service which runs continuously. System under question is an embedded linux built by Yocto.
If the service stops for any reason (either failure or just completed), it should be restarted automatically
If restarted more than X times, system should reboot.What options are there for having this? I can think of the following two, but both seem suboptimal
1) having a cron job which will literally do the check above and keep the number of retries somewhere in /tmp or other tmpfs
2) having the service itself track the number times it has been started (again in some tmpfs location) and rebooting if necessary. Systemd would just have to continuously try to start the service if it's not runningedit: as suggested by an answer, I modified the service to use theStartLimitActionas given below. It causes the unit to correctly restart, but at no point does it reboot the system, even if I continuously kill the script:[Unit]
Description=myservice system
[Service]
Type=simple
WorkingDirectory=/home/root
ExecStart=/home/root/start_script.sh
Restart=always
StartLimitAction=reboot
StartLimitIntervalSec=600
StartLimitBurst=5
[Install]
WantedBy=multi-user.target
|
Systemd - always have a service running and reboot if service stops more than X times
|
I can keep it very short. You will need to use PHP to execute the console.* * * * * php -q /usr/bin/php /var/www/myProject/bin/console desktop:auction_end > /dev/nullWriting the output of a cron job that you are testing to a file will help you debug errors. All output is now lost in the void :)* * * * * php -q /usr/bin/php /var/www/myProject/bin/console desktop:auction_end > /home/<user>/crons/auction_end.cron.txtEditIt might be that yourphpshould be used as absolute path.* * * * * /path/to/php /path/to/bin/console symfony:commandOr even by specifying the user to execute the command with:* * * * * root /usr/bin/php /path/to/bin/console command:to:executeAlso make sure that the root user has permission to execute files in your symfony project.
|
I have this simple command in symfony :use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class AuctionEndCommand extends Command
{
protected function configure()
{
error_log(print_r('test',true), 3, "/tmp/error.log");
$this->setName('desktop:auction_end')->setDescription('Execute when auction is end.')->setHelp("Identify winners for auctions");
}
protected function execute(InputInterface $input, OutputInterface $output)
{
// outputs multiple lines to the console (adding "\n" at the end of each line)
$output->writeln([
'User Creator',
'============',
'',
]);
// outputs a message followed by a "\n"
$output->writeln('Whoa!');
// outputs a message without adding a "\n" at the end of the line
$output->write('You are about to ');
$output->write('create a user.');
}
}Now when I execute :/var/www/myProject/bin/console desktop:auction_endthis command works fine. But when I try to execute as a cron in linux this script doesn't start :In linux as sudo I did :nano crontab -e, and the cron :* * * * * /usr/bin/php /var/www/myProject/bin/console desktop:auction_end > /dev/nullWhat I'm doing wrong, can you help me please ? Thx in advance and sorry for my english
|
How to execute a Symfony command as cron job?
|
+25Unfortunately the wp_schedule_event doesn't have 30 min and accepts only these intervals: hourly, twicedaily(12H), daily(24H).In my opinion is a bit strange to have a scheduled event that can change randomly, and probably you should look at a different implementation.
Without discussing your choice I am going to provide a possible answer.There are plugins with hooks into the Wordpress cron system to allow different time interval.One solution is to set only one cron every 30 minutes and have a custom function that randomly will be executed or not.if (rand(0,1)) { ....For example:after 30 min the function will be executed (and you have 30 min cron)after another 30 min the function simply skip the runfor the next 30min will be triggered again and executed(and you have your 1 hour cron).The problem there is to force the execution at 1 hour (after 1 skip), because you can end up to skip more than +30min. This can be achieved storing the value of the last execution.Another solution is to have 2 cron (30 min and 1 hour) nearly in the same time and having a custom function that will trigger the 30 min if the 1 hour is not running and so on.Here is a niceWordpress cronjob pluginIf you need to store the cron execution safely in a Wordpress table you can use theWordpress add_option function, with get_option and update_option to get and update its value.
|
Is is possible to start the WP-Cron randomly between 30 and 60 minutes?What i haveadd_action('my_hourly_event', 'do_this_hourly');
function my_activation()
{
if(!wp_next_scheduled( 'my_hourly_event' ))
{
wp_schedule_event( current_time( 'timestamp' ), 'hourly', 'my_hourly_event');
}
}
add_action('wp', 'my_activation');
function do_this_hourly()
{
// do something
}
|
Wordpress wp_schedule_event randomly between 30 and 60 minutes
|
What you actually want is to run your worker as adaemon. The basic idea is to run your task in a loop without any user interaction and write the output into a log file.This is a complex task and depending on the programming language of your choice there might be a library that will handle that for you.PHP:PHP-DaemonRuby:Ruby-DaemonsPython:Stackoverflow answerJava:Apache Commons daemonAnother useful approach specific to RabbitMQ is to run your worker code as command line program with theRabbitMQ-cli-consumer. This approach will work for any programming language with cli support. Especially for script languages with stability issues like PHP this will be the favorable way to go.
|
I am implementing rabbitMQ with more than 3 workers processing. To test it, I need to execute worker file each time, but I don't want that.I want my worker script to listen all request continuously without manually executing worker file. Many people suggested CRON but I don't want because if previous run hasn't finished then overlap can cause serious issues.Is there any way to run my worker script continuously in background?
|
How to make RabbitMQ worker listening continuously ?
|
There's nothing I know of and I also didn't find anything with Google. You may be able to hack something together on your own though:>> cron = "*/10 * * * 1,3 foo"
#=> "*/10 * * * 1,3 foo"
>> min, hour, dom, month, dow, command = cron.split
#=> ["*/10", "*", "*", "*", "1,3", "foo"]Once you have the vars, you can start assembling the parts for your output:>> require 'date'
#=> true
>> dow.split(/,/).map { |day| Date::DAYNAMES[day.to_i] }
#=> ["Monday", "Wednesday"]
>> min.start_with?('*') ? "every #{min.split('/')[1]} minutes" : "#{min} past"
#=> "every 10 minutes"
>> min = '5'
#=> "5"
>> min.start_with?('*') ? "every #{min.split('/')[1]} minutes" : "#{min} past"
#=> "5 past"Obviously that's just some rough ideas (for example you may want a regex with capture groups for parsing the entry), but since the crontab entries are well specified, it shouldn't be too hard to come up with something that works for most of the entries you are likely to encounter.
|
Is there a ruby gem/plugin which will convert something like */10 * * * 1,3 to "Triggers every 10 minutes on Monday, Wednesday" ?
|
ruby plugin/gem to convert cron into a human readable format
|
Have you tried using CURL instead?
|
I am trying to manage a queue of files waiting to be processed by ffmpeg. A page is run using CRON that runs through a database of files waiting to be processed. The page then builds the commands and sends them to the command line usingexec().However, when the PHP page is run from the command line or CRON, it runs theexec()OK, but does not return to the PHP page to continue updating the database and other functions.Example:<?php
$cmd = "ffmpeg inpupt.mpg output.m4v";
exec($cmd . ' 2>&1', $output, $return);
//Page continues...but not executed
$update = mysql_query("UPDATE.....");
?>When this page is run from the command line, the command is run usingexec()but then the rest of the page is not executed. I think the problem may be that I am running a command usingexec()in a page run from the command line.Is it possible to run a PHP page in full from the command line which includesexec()?Or is there a better way of doing this?Thank you.
|
Running PHP from command line
|
thanks.. I find it out..either I need to specify the node path or
do that in the sh script:nodejs/node myscript.jswhere nodejs/node is where the node installed.
|
I have a cron job that call a shell script.*/2 * * * * sh cron_test.sh >> output.logIn side the shell script, I run some command lines like:#!/usr/bin
./mongo/bin/mongodump .....
FILE_NAME='abc'
node mynode.js $FILENAMEIt runs if I just call cron_test.sh in command prompt. However, it doesn't run node if it is run by cronjob. It does run the mongodump command. So, what's wrong? is there anything I have to set for permission, etc?
|
How to run a Cron job for Node.js
|
If you have access to Cron, I highly recommend Wheneverhttp://github.com/javan/wheneverYou specify what you want to run and at what frequency in dead simple ruby, and whenever supplies rake tasks to convert this into a crontab and to update your system's crontab.If you don't have access to frequent cron (like I don't, since we're on Heroku), then DJ is the way to go.You have a couple options.Do what you're doing. DJ will retry each task a certain number of times, so you have some leniency therePut the code that creates the next DJ job in an ensure block, to make sure it gets created even after an exception or other bad eventCreate another DJ that runs periodically, checks to make sure the appropriate DJs exist, and creates them if they don't. Of course, this is just as error prone as the other options, since the monitor and the actual DJ are both running in the same env, but it's something.
|
I'm using Delayed Job to manage background work.However I have some tasks that need to be executed at regular interval. Every hour, every day or every week for example.For now, when I execute the task, I create a new one to be executed in one day/week/month.However I don't really like it. If for any reason, the task isn't completely executed, we don't create the next one and we might lose the execution of the task.How do you manage that kind of things (with delayed job) in your rails apps to be sure your regular tasks list remains correct ?
|
Regular delayed jobs
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.