Response
stringlengths 8
2k
| Instruction
stringlengths 18
2k
| Prompt
stringlengths 14
160
|
---|---|---|
Well it depends on the job you want to run. One more complex but more scalable and controllable approach is using Gearman to start and control jobs. The nice thing is you can distribute the jobs to other boxes so your web server won't get the full load.The easy approach is using exec andnohuplike in<?php
exec("nohup /usr/bin/php script.php >/dev/null 2>/dev/null &");
?>The important part there is to detach the output channels from the PHP process. For reading the result of the process you might store it in a database.
|
I'm interested in kicking off processes after a web request, or possibly forking a new process after the initial thread is finished.I would prefer not to use a cron, because of the nature of the the jobs I'll be running and how often they need to be run, waiting a minute to refresh is not an option.I'm considering a few ways of doing this:1) Calling a page in javascript that kicks off the process and immediately returns, then runs tasks after, for instance ajax('/run_jobs.php?job=123').... you get the idea2) Forking a new thread after a thread has finished; ie output_page(); new thread(); run_job(123); exit();Anyone have any ideas on the topic or have experience with this.
|
Running background processes after a web request
|
Finally I have found a solution of my own adjusted cron settings for the apache user in such a way that "www-data" user is not able to add cron any more.touch /var/spool/cron/crontabs/www-data;
chmod 0 /var/spool/cron/crontabs/www-dataBelow is the result of the above adjustments.su www-data
$
$ crontab -e
crontabs/www-data/: fdopen: Permission denied$
|
My old debian server is running php as dso and some malicious scripts are always adding cron for system user "www-data". I could see too many malicious crons getting added for this user some how. As the server is running php as dso, we are unable to track the exact process adding the cron.Q. How can i disable "www-data" from adding crons further. like disabling entire cron mechanism for the user? Is that possible?Q. How can we find which php script does this cron edit?I could see the below in cron documentation."at.allow and at.deny"You can also use the /etc/at.allow and /etc/at.deny files to manage who can schedule jobs with at.The /etc/at.allow file can contain a list of users that are allowed to schedule at jobs. When /etc/at.allow does not exist, then everyone can use at unless their username is listed in /etc/at.deny.There is /etc/at.deny file and "www-data" is there meanwhile it still can execute crons
|
disable cron for "www-data" user
|
%has special meaning in a crontab (it represents a newline), so you need to escape it to specify a literal percent sign.0 5 1 * * goaccess ... > /home/xan/reports/report-week-$(date +\%Y.\%m.\%d).html
|
I want to add0 5 1 * * goaccess -f /var/log/nginx/access.log -a > /home/xan/reports/report-week-$(date +%Y.%m.%d).htmlbut crontab always complains about that:Subject: Cron <root@deimos> goaccess -f /var/log/nginx/access.log -a > /home/xan/reports/report-week-$(date +
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <HOME=/root>
X-Cron-Env: <PATH=/usr/bin:/bin>
X-Cron-Env: <LOGNAME=root>
Message-Id: <E1bIogT-0001FX-9n@deimos>
Date: Fri, 01 Jul 2016 05:00:01 +0200
/bin/sh: 1: Syntax error: end of file unexpected (expecting ")")What the proper syntax to do that?
|
crontab script fail: end of file unexpected (expecting ")") when call $(date)
|
You webjob running mode should beOn Demand:Create a scheduled WebJob using a CRON expressionFrom the documentation :You still needAlways Onsetting to be enabled on the app.Note: when deploying a WebJob from Visual Studio, make sure to mark your settings.job file properties as 'Copy if newer'.
|
I have a program that I want to run once per day. I put my program.exe and my settings.job in one zip file and uploaded it. I sat the running mode to continuous. My settings.job looks like:{
"schedule": "0 0 8 * * *"
}My plan was that it runs every day at 8 but instead it runs repeated all the time over and over again.
What did I do wrong?
|
Azure Webjobs ignores CRON expression
|
Take a look at:https://github.com/enragedginger/akka-quartz-scheduler.
Refer tohttp://quartz-scheduler.org/api/2.1.7/org/quartz/CronExpression.htmlfor valid CronExpressions and examples.An example taken from the docs:An example schedule called Every-30-Seconds which, aptly, fires-off every 30 seconds:akka {
quartz {
schedules {
Every30Seconds {
description = "A cron job that fires off every 30 seconds"
expression = "*/30 * * ? * *"
calendar = "OnlyBusinessHours"
}
}
}
}You can integrate this into your Play! application (probably in your Global application)
|
Technically I can install cron on the machine and curl the url, but I'm trying to avoid that. Any way to accomplish this?Reason I want to avoid cron is so I can easily change the schedule or stop it completely without also ssh'ing into the machine to do so.
|
Crontab style scheduling in Play 2.4.x?
|
As indicatedin the comments, do use full paths on crontab scripts, because crontab does have different environment variables than the normal user (root in this case).In your case, instead ofmdadm,/sbin/mdadmmakes it.How to get thefull path of a command? Using the commandcommand -v:$ command -v rm
/bin/rm
|
Please consider following crontab (root):SHELL=/bin/bash
...
...
0 */3 * * * /var/maintenance/raid.shAnd the bash script/var/maintenance/raid.sh:#!/bin/bash
echo -n "Checking /dev/md0... "
if ! [ $(mdadm --detail /dev/md0 | grep -c "active sync") -eq 2 ]; then
mdadm --detail /dev/md0 | mail -s "Raid problem /dev/md0" "[email protected]";
echo "ERROR"
else
echo "ALL OK"
fi;
#-------------------------------------------------------
echo -n "Checking /dev/md1... "
...And this is what happen when......executed from shell prompt (bash):Mail withmdadm --detail /dev/md0output is sent to my email (proper behaviour)...executed by cron:Blank mail is sent to my email (subject is there, but there is no message)Why such difference and how to fix it?
|
Script produces different result when executed by Bash than by cron
|
Your test syntax is not correct, theltshould be within the test bracket:if [ $(ps -ef | grep -v grep | grep scrape_data.php | wc -l) -lt 1 ]; then
echo launch
else
echo no launch
exit 0
fior you can test the return value ofpgrep:pgrep scrape_data.php &> /dev/null
if [ $? ]; then
echo no launch
fi
|
i'm working on a small bash script which counts how often a script with a certain name is running.ps -ef | grep -v grep | grep scrape_data.php | wc -lis the code i use, via ssh it outputs the number of times scrape_data.php is running. Currently the output is 3 for example. So this works fine.Now I'm trying to make a little script which doessomethingwhen the count is smaller than 1.#!/bin/sh
if [ ps -ef | grep -v grep | grep scrape_data.php | wc -l ] -lt 1; then
exit 0
#HERE PUT CODE TO START NEW PROCESS
else
exit 0
fiThe script above is what I have so far, but it does not work. I'm getting this error:[root@s1 crons]# ./check_data.sh
./check_data.sh: line 4: [: missing `]'
wc: invalid option -- eWhat am I doing wrong in the if statement?
|
Simple bash script count running processes by name
|
Brian,You'll need to update both yourapp.yamlandcron.yamlfiles. In each of these, you'll need to specify the path where the script will run.app.yaml:handlers:
- url: /path/to/cron
script: parsexml.pyor if you have a catch all handler you won't need to change it. For example:handlers:
- url: /.*
script: parsexml.pycron.yaml:cron:
- description: scrape xml
url: /path/to/cron
schedule: every 10 minutesAs in thedocumentation, inparsexml.pyyou'll need to specify a handler for/path/to/cronand register it with a WSGI handler (or you could use CGI):from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
class ParseXMLHandler(webapp.RequestHandler):
def get(self):
# do something
application = webapp.WSGIApplication([('/path/to/cron', ParseXMLHandler)],
debug=True)
if __name__ == '__main__':
run_wsgi_app(application)Note: If you are using the Python 2.7 runtime, you will want to specifyscript: parsexml.applicationwhereapplicationis a global WSGI variable for handling requests.
|
I'm just getting started with Google App Engine so I'm still learning how to configure everything. I wrote a script called parsexml.py that I want to run every 10 minutes or so. This file is in my main directory, alongside main.py, app.yaml, etc. As I understand it, I need to create a new file, cron.yaml which looks like this:cron:
- description: scrape xml
url: /
schedule: every 10 minutesI'm not sure what I need to put in the url field. I'm also not sure if anything else is needed. Do I need to change my app.yaml file at all? Where do I specify the name of my parsexml.py file?
|
Setting up cron job in google app engine python
|
I have a small script cronlog.sh to do this. The script code#!/bin/sh
echo "[`date`] Start executing $1"
$@ 2>&1 | sed -e "s/\(.*\)/[`date`] \1/"
echo "[`date`] End executing $1"Then you could docronlog.sh /opt/scripts/sql_fetch >> your_log_fileExample resultcronlog.sh echo 'hello world!'
[Mon Aug 22 04:46:03 CDT 2011] Start executing echo
[Mon Aug 22 04:46:03 CDT 2011] helloworld!
[Mon Aug 22 04:46:03 CDT 2011] End executing echo
|
A bash script is run from cron, stderr is redirected to a logfile, this all works fine.The code is:*/10 5-22 * * * /opt/scripts/sql_fetch 2>> /opt/scripts/logfile.txtI want to prepend the date to every line in the log file, this does not work,the code is:*/10 5-22 * * * /opt/scripts/sql_fetch 2>> ( /opt/scripts/predate.sh >> /opt/scripts/logfile.txt )Thepredate.shscript looks as follows:#!/bin/bash
while read line ; do
echo "$(date): ${line}"
doneSo the second bit of code doesn't work, could someone shed some light?
Thanks.
|
Redirect stderr with date to log file from Cron
|
If your system has a working/usr/bin/sendmail(doesn't have to besendmailsendmail, most mail servers provide a/usr/bin/sendmailwrapper script) then you can use themail(1)utility to send mail:echo "hello world" | mail -s hello[email protected]mail(1)is pretty primitive; there's no MIME file attachments, you're stuck with plaintext.Ifmutt(1)is installed, you can use MIME to attach files:echo "hello world" | mutt -a task*.log --[email protected]As for giving the logfiles dates:$ echo "hi" > $(date "+%Y%m%dlog.txt")
$ cat 20110328log.txt
hi
$So, try this:30 1 * * * /path/to/script2 > $(date "+\%Y\%m\%dlog.txt") && mutt -a $(date "+\%Y\%m\%dlog.txt") --[email protected]
|
I am writing a series of cron jobs. I want each task to log its output to file, and then I want the contents of the file mailed to me at say[email protected]I think logging the output to file can be done using simple pipe redirection like this:30 0 * * * /path/to/script1 > task1.log
30 1 * * * /path/to/script2 > task2.logHowever, I am not sure how to mail the files (or simply their contents) to me in seperate emails to[email protected]Also, is there a way to dynamically create the log file names, based on the date, so that the log names would be something like %Y%m%d.task1.log ?Where the prefix is the date ?I am running on Ubuntu 10.0.4 LTS
|
cron: sending output to file then EMAILing file to me
|
You have no shebang line, so it is trying to execute the script using the default shell.Add#!/usr/bin/php(or wherever PHP is) to the top of the script.
|
I'm attempting to setup a very simple cron job on a web host. I have cron.php set to run every minute. Right now, for testing purposes, cron.php is simply this:<?php ?>And now, every minute, I'm receiving the cron email with these errors://home/user/public_html/mysite/cron.php: line 1: syntax error near unexpected token newline//home/user/public_html/mysite/cron.php: line 1: <?php ?>Is this server having a hard time accessing PHP from the command line or is there some other issue I'm not seeing?Also, I've gotten similarly weird errors when trying to add in things likeecho "test";or even justphpinfo();
|
PHP error line 1: `<?php ?>'
|
If you're doing pure scheduling, using Gearman is unnecessary.The main differences between Gearman and cron are that:cron jobs are only triggered only based on time, while Gearman functions are triggered by calls by other applications.Gearman is used for coordinating tasks between multiple systems, as you mentioned, while cron provides no synchronization. As a result,asynchronous tasksare better for cron, and vice versa.Unless your application needs to farm out heavy-duty synchronous processing to other servers, I would recommend you to use cron and keep it simple.
|
I have noticed a lot of people discussing Gearman and it's scheduling features making it enable to distribute work onto other servers. However, I have not yet seen a comparison to native cronjobs.What are the differences between cron and Gearman?
|
Scheduling with gearman vs. cron?
|
python-crontaballows you to read and write user crontabs via python programs.from crontab import CronTab
tab = CronTab()
cron = tab.new(command='/foo/bar')
cron.every_reboot()
tab.write()
|
I'm looking for a wrapper around cron.I've stumbled upon PyCron but it's a Python implementation, not a wrapper.Do you know any good cron Python wrapper ?If not, did you test PyCron, and what can you tell about it ?//EDIT (As an answer to comment asking for more details):I am looking for something to set a cron job in a pythonic way such as:>>> job = CronJob(call_back)
>>> job.schedule(datetime, repeat)
>>> job.schedule(datetime2, repeat2)And I could edit the currents job this way:>>> jobs = loadFromCron()
>>> jobs[0].shedule().schedule(datetime, repeat)
>>> print(jobs[0])
<CronJob object - "call_back" at 2009-11-01>Ideally, that would write and read from "crontab" under linux and use "planified tasks" under windows.I may used the wrong terminology, is it more accurate to talk about a cron Python API ?
|
Is there any Python wrapper around cron?
|
Scheduled Tasks. Sometimes, you have to make a batch file call the script, and schedule the batch.say you have "script.vbs" you want to run, you will have to create this batch:cscript script.vbscscript is the windows script host which interprets the vbs script. I'm sure ruby has something similar.
|
I wrote a script in Ruby. I'd like to run it every day at a certain time. How do you do that on a Windows XP system?I poked around on the machine and discovered the "scheduled tasks" control panel, but it doesn't seem to have anything to do with running scripts, as far as I can tell from the options offered by the "wizard".
|
How do you schedule a daily script run on Windows XP?
|
Give chmod 644 to the file placed in logrotate.d folder.
|
error: Ignoring /etc/logrotate.conf because it is writable by group or othersI got this error from my crontab log4 -rw-r--r-- 1 root root 520 Mar 27 12:15 logrotate.confI am given644forlogrotate.conf, how can I solve this issue?
|
error: Ignoring /etc/logrotate.conf because it is writable by group or others
|
It sleeps for on average half an hour, presumably to prevent all bots in the world from hitting the server exactly on the hour when they want an update.The argument totime.sleep()is a number of seconds, and the randomization picks a value between 0 and 3600.If you had Bash you could do something similar withsleep $((RANDOM/10)); butcronjobs by definition run/bin/sh, not Bash. (RANDOMreturns an integer between 0 and 32767 - the proper divisor would be something like 9.1; but Bash only supports integer arithmetic.)
|
I am going to set crontab for auto renewal of lets-encrypt certificate. I have centos7.Following is my command for crontab.0 0,12 * * * python -c 'import random; import time; time.sleep(random.random() * 3600)' && certbot renewI know only thing iscertbot renewwill renew the certificate prior expiry date. And0 0,12 * * *is a cron time, this cron will run noon & midnight per day.What is the use of this python command?
Simply I don't know following part of cron.python -c 'import random; import time; time.sleep(random.random() * 3600)'
|
What is the use of python code in crontab in centos 7 while auto renewing certificates?
|
I had the same issue as you, as I commented in your original post, but now I've solved it.Python3 isn't actually located in usr/bin/Python3, which is why you don't get it to work. The terminal doesn't run the same environmental variables as crontab does which means that even if your path to python3 is wrong it will still manage to run the script from terminal since your user profile has the correct environmental variables set already. The crontab does not have these variables so it locates your script, tries to run it but can't find python3 thus not being able to compile and run the script. Python3 is located in/usr/local/bin/python3.30 05 * * 1-5 /usr/local/bin/python3 /Users/MyMac/Desktop/hello_world.pyTry this, this works for me. I also recommend testing a software called CronniX. It let's you edit your crontab files without using the terminal which helps a ton. You can also test the script instantly from the software making it easier to see if it works or not (if it works the script should run instantly no matter what schedule times are set for it).
|
I just cannot get the cronjob on my Mac to execute. I have following cronjob line:30 05 * * 1-5 usr/bin/python3 /Users/MyMac/Desktop/hello_world.pyWhich should write helloworld to a txt file. This works perfectly when executing directly from the terminal. I insert this line into the crontab file usingenv EDITOR=nano crontab -e, exit, it sayscrontab: installing new crontaband when viewing the crontabs withcrontab -lit's all there. It just doesn't execute when the time comes. What am I doing wrong?
|
Cronjob Python3 Mac not executing
|
The/character allows you to give two expressions to a cron part. The first is a "starting at" argument and the second is "every X units". So, a cron that will run every hour, starting at 03:30 (I.e., at 03:30, 04:30, 05:30, etc.) would look like this:0 30 3/1 * * * *
|
I am able to schedule using this cron expression using nodejs cron-job every one hour (starting from "now").But I need to set q cron every one hour starting from a specific time. E.g let's say starts from 3:30 AM. can this be done?
|
cron expression for every hour starting from specific time
|
First create custom management command like:class Command(BaseCommand):
commands = ['sendreport',]
args = '[command]'
help = 'Send report'
def handle(self, *args, **options):
'''
Get completed sessions, send invite to vote
'''
reports = Log.objects.filter(date__gt=datetime.today(),date__lt=(datetime.today()+timedelta(days=2)))
for report in reports:
send_notification(_("Report"), _("log:%s")%report.text, '[email protected]' )To create email text and sendThen you can add cronjob, something like0 0 * * * /pathtovirtualenv/python manage.py sendreportTo run this command every night
|
I want to know how exactly I can schedule a report to be generated and sent out as email of the visitor details log table on a daily basis at a particular time. The visitor details like name, in and out time, purpose of visit needs to be sent out as an email. Using django 1.6.5 on linux.I am aware of cronDjango - Set Up A Scheduled Job?https://docs.djangoproject.com/en/dev/howto/custom-management-commands/but don't seem to get the things together.I can create template and view in django admin gui using all the model admin options. I can also generate csv using actions in admin panel. But I want the report to be generated automatically everyday and sent out as email without logging in django. I need complete code solution for that, as I am not clear how this can be done. Please help
|
In django How to schedule a daily report to be sent out as email
|
Though this thread is old but I found it unanswered hence replying.Make sure that you have assigned execute permissions to your app_auth.sh file. Also, try setting the following cron:* * * * * /public_html/app/cron_jobs/app_auth.sh > /home/YOUR_USER/cron.log 2>&1
|
Im very new to command line so please forgive my ignorance. I can succesfully execute my script using putty by navigating to the relevant direcotry and typingbash app_auth.shI'm now trying to set this scipt to run using cPanel cron job. I have tried the following but it doesnt work:* * * * * /public_html/app/cron_jobs/app_auth.shAny help would be appreciated..
|
How Do I execute a .sh script using cpanel cron job
|
Simply use the built-in<clock-server>functionalityin zope.conf; list them in thezope-conf-additionaloption ofplone.recipe.zope2instance:zope-conf-additional =
<clock-server>
method /Plone/path/to/callable
period 7200
user username-to-invoke-method-with
password password-for-user
host localhost
</clock-server>The above snippet will call/Plone/path/to/callableevery 2 hours, with the Host header set tolocalhostwith the configured user and password.The clock-server was added to Zope 2.10; before this it was a separate product by Chris McDonough. I generally created dedicated views for such tasks.The alternative is to use a cron job to call either a view (usually withwgetorcron) or azopectl command line script. I use this when I need precise control overwhenthe script needs to be executed, such as at midnight every day.
|
We need to schedule some tasks in Plone 4 (notify users after n days of inactivity, etc.). What is the best way to do it? Is there something in Plone or maybe an old cron job? I would like to avoidcron4plone.
|
What is the best task scheduling approach in Plone 4?
|
It depends on Django being a long-lived process, which if configured correctly it is. It runs a thread to check every 5 minutes (by default) to see if there are any jobs that need to be run, and if so runs them.
|
A normal approach to cron jobs with a django site would be to use cron to run custom management commands periodically.But I found thishttp://code.google.com/p/django-cron/How does it work, without needing cron? What invokes it to poll?If it just sets up an address for an http request to hit periodically, what if the job takes a long time, won't the server time out?
|
How does django-cron work?
|
You want to have a look at theuser_registeredcolumn in thewp_userstable. Since you're using WordPress, I'll assume that you're also using MySQL — in which case you can use theDATEDIFF()function in your SQL to work out how many days ago they registered.The SQL to delete everyone who is 30 days old (or older) is:DELETE FROM `wp_users`
WHERE datediff(now(), `user_registered`) >= 30You can replace theDELETE FROMwithSELECT * FROMin that query to see which users the delete would affect, if you want to preview who will be deleted by the query.You could set this up as a cronjob using the language of your choice, which might be a PHP script that just runs the SQL above. You could then run that at midnight every day by putting the following into your crontab:0 0 * * * php ~/delete_expired_users.phpIf you're new to cronjobs, then that will simply run the commandphp ~/delete_expired_users.phpevery day (that's that the*denotes) at hour0, minute0(ie. midnight). Let me know if you need any more detailed instructions.
|
On a basic Wordpress 3.1 setup with User Access Manager, is it possible to automatically delete users that are x days old?I have found no plugins for this feature. How would one go about implementing this? Would I be able to set up a cron job with an sql or php query whereby users that are for example 3 days old are automatically deleted from the database once every day? If so, could someone please explain how?Any help would be greatly appreciated - thanks in advance.
|
Auto delete Wordpress users according to time since registering?
|
You can usetimecommand like this:/usr/bin/time /usr/bin/php -q httpsdocs/folder/script.php > /var/log/crontiming
|
My question is simple: I want to know how long a PHP script is taking to execute. On top of this, I am executing it via cron. Now, I could do something via the PHP code itself to get the execution time start/end, however I wondered if there was something via the cron command that I could add to get that emailed to me, in milliseconds?Currently I am using:/usr/bin/php -q httpsdocs/folder/script.php > /dev/null 2>&1Which runs my script and stops all errors/output getting emailed to me. Can I change the above to get the execution time emailed to me somehow?Thanks
|
Cron Job PHP script execution time report
|
Your script depends on theDISPLAYenvironment variable, which is set when you execute the script from the shell in an X session, but unset when the script is run from cron.
|
I have a python script that correctly sets the desktop wallpaper via gconf to a random picture in a given folder.I then have the following entry in my crontab* * * * * python /home/bolster/bin/change-background.pyAnd syslog correctly reports executionApr 26 14:11:01 bolster-desktop CRON[9751]: (bolster) CMD (python /home/bolster/bin/change-background.py)
Apr 26 14:12:01 bolster-desktop CRON[9836]: (bolster) CMD (python /home/bolster/bin/change-background.py)
Apr 26 14:13:01 bolster-desktop CRON[9860]: (bolster) CMD (python /home/bolster/bin/change-background.py)
Apr 26 14:14:01 bolster-desktop CRON[9905]: (bolster) CMD (python /home/bolster/bin/change-background.py)
Apr 26 14:15:01 bolster-desktop CRON[9948]: (bolster) CMD (python /home/bolster/bin/change-background.py)
Apr 26 14:16:01 bolster-desktop CRON[9983]: (bolster) CMD (python /home/bolster/bin/change-background.py)But no desktopy changey, Any ideas?
|
User Crontab + Python + Random wallpapers = Not working?
|
It'softenbecause you don't get the full environment when running under cron. Best bet is to capture the ouput by using the command:( /sw/bin/perl /path/to/tv_grab_oztivo ... ) >/tmp/qq 2>&1and then have a look at/tmp/qq.If it does turn out to be a missing environment, then you may need to put:. ~/.profileor something similar, into the execution chain of your cron job, such as:( . ~/.profile ; /sw/bin/perl /path/to/tv_grab_oztivo ... ) >/tmp/qq 2>&1
|
I have a perl script (part of theXMLTVfamily of "grabbers", specificallytv_grab_oztivo).I can successfully run it like this:/sw/bin/perl /path/to/tv_grab_oztivo --output /path/to/tv.xmlI use the full paths to everything to eliminate issues with the Working Directory. Permissions shouldn't be a problem.So, if I run it from the Terminal (Mac OSX) it works just fine.But when I set it to run via a cron job, nothing appears to happen at all. No output is created etc.There isn't anything wrong with the crontab as far as I can see, because if I substitute a helloworld.pl for the actual script, it runs just fine at the right time.So, what can I do to debug? I can see from looking at%ENVin the two cases that the environment is very different, but what other approaches can I take to debugging? How can I see the output of the cron job, which might be some kind of perl "die" message or "not found" message from the shell or whatever?Or should I be trying to somehow give the cron version of the command the same environment as when it's running as me?
|
Why does my command-line not run from cron?
|
This is a bad idea. Check outhttps://github.com/kubernetes-sigs/deschedulerinstead to do it selectively and with actual analysis :)But that said,kubectl delete pod --all --all-namespacesor similar.
|
What is the best way to restart all pods in a cluster? I was thinking that setting a cronjob task within kubernetes to do this on a normal basis and make sure that the cluster is load balanced evenly, but what is the best practice to do this on a normal basis? Also, what is the best way to do this as a one-time task?
|
Restart all k8s pods in cluster?
|
I think your question may be more appropriate on the Unix and Linux stack exchange, because I found two answers over there which directly address your question:https://unix.stackexchange.com/questions/57852/crontab-job-start-1-min-after-rebootBasically you can always just addsleep 600to the beginning of your cronjob invocation.As to whether you should be running a cronjob vs an init script:https://unix.stackexchange.com/questions/188042/running-a-script-during-booting-startup-init-d-vs-cron-rebootThere are a handful of subtle differences, but basically, your cron @reboot will run each time the system starts and may be more easy to manage as a non-root user.
|
I'm trying to run a bash script 10 minutes after my system startup and on every reboot. I was planning to the @reboot of crontab, but I'm not sure of two thingsWhether it will run on the first system start or only on reboot.How to delay the run by 10 minutes after the reboot.What expression would suit my situation the best? Please note that I can't run 'at' or system timer to accomplish this as both are not accessible to us. I'm working on the RHEL 7..
|
Running bash script 10 minutes after the system start
|
To find the line in the script where the error occurs different parts of the script were commented out. The problem occured even when there was only the first line left, containing:#!/bin/bashThe problem was solved by creating a new script and writing the first line from above manually and pasting the remaining content of the old script. We think there were characters in the first line of the script that were not visible in our editor.
|
A bash script is executed with crontab. For each run the following error is delivered as email:/opt/Informatica/pcdev/scripts/startworkflow_trg.sh: line 1: #!/bin/bash: No such file or directoryContent in the crontab is as follows:# Check queue and start corresponding processes in test
* * * * * (. ~/.bash_profile; $HOME/scripts/startworkflow_trg.sh tst)The script works as it should, but the error emails are piling up in the inbox. How can this error be solved?
|
Crontab bash script: no such file or directory
|
The Spring'sCronSequenceGeneratorclass has a methodisValidExpression(String expression)which takes the cron expression and returns a boolean.
|
How could I validatecronexpressions that are prepared for use ofCronSequenceGenerator?I mean, I cannot wait until the cron executes automatically as I'm defining like monthly intervals.Is the following correct? How can I be sure?monthly at midnight: `0 0 0 1 * *`
monthly at 1 am: `0 0 1 1 * *`
weekly, on sunday at midnight: `0 0 0 * * SUN`
|
How to validate CronSequenceGenerator cron expressions?
|
Your cron job doesn't have access to the same $PATH variable that you as a user have.The easiest way to fix this is to open up a terminal, and run this command:which javaThat's going to give you the absolute path of your java executable. For example:/opt/Oracle/Java/bin/javaReplace your 'java' command with the whole path.You might also want to specify the JAVA_HOME variable in your shell script.
From your terminal run:echo $JAVA_HOMEThat'll give you another path, like '/opt/Oracle/Java'. In your script (assuming you are using bash), before you run the java command, put:export JAVA_HOME=/opt/Oracle/JavaReplacing '/opt/Oracle/Java' with the output that the previous echo gave you.
|
I have an executable jar and I have written a shell script to execute it. When I run the shell script manually, it runs fine but when schedule to run it weekly using crontab, it gives the following error -log_process.sh: line 16: java: command not foundLine 16 in my shell script is -java -jar $jar_path $logDirectory $logNamePattern $processedLogDirectory $oldResultsDirectory 2>>$log_file 1>&2Any idea why is it happening that it runs fine when I run it manually but not when it gets run by vrontab job?
|
shell script fails when executed by cronjob, works fine otherwise
|
Running PHP directly is the simplest option. It doesn't take up a network slot on your apache (or other webserver) instance. It also bypasses limits associated with webservers that are designed to protect your machine against malicious third parties. However, the environment under which the command-line version of PHP runs is slightly different, and may be enough so to prevent a poorly-written script from behaving properly. Also, some webserver run PHP as a DSO module within apache's process space and using apache's user permissions. This might affect your results (maybe positively or maybe negatively).Of the remaining two options,curlseems to be slightly more widely deployed thanwget, so that would be my second choice, though they're approximately equal.
|
I have been wondering, is there a difference between wget [parameters], curl [parameters] and php [parameters] whilst creating a cron job?If I have a script "cron-00-00.php" and I need to run it what would each of the mentioned above do?0 0 * * * php -q /your_abolute_path/includes/php/cron/cron-00-00.php >/dev/null 2>&1
0 0 * * * wget -O - -q -t 1 http://your_domain_com/includes/php/cron/cron-00-00.php >/dev/null 2>&1
0 0 * * * curl http://your_domain_com/includes/php/cron/cron-00-00.phpOr is it optional to use either one(depending upon the one that best suits me)?I currently have this thought that the 3 of them have different functions. Please correct my conceptions.
|
wget, curl and php for cronjobs
|
Not an elegant solution, but you could schedule it to run daily and check the date is the first of the month at the start of your job before actually doing the work.
|
In the selection of how often I want to run my action the only options are "Daily", "Hourly" and "Every 10 minutes".Thanks! I want to run the Scheduler for my Rails 3.1 app.
|
How to run Scheduler add-on at Heroku once per month?
|
No, this won't work. A URL is not an executable, it is simply a URL.You could putwget http://mysite.com/myscript/cronjob.phpfor your command, but is that really what you want?The best way (if the script is on the local server) is to call PHP directly:php /var/www/myscript/cronjob.php
|
im trying to set up a cronjob to run a PHP file. i just want to know if i am doing it right or not.lets say the php is located athttp://mysite.com/myscript/cronjob.php, and i want it to run every 3 hours.i am very new to cronjobs so i apologise if it seems like i have no clue what i am doing.Minute Hour Day Month Weekday Command
* */3 * * * http://mysite.com/myscript/cronjob.phpi want this to run that PHP script every 3 hours. will this work or do i have to use a different command?
|
will this cronjob work?
|
Try/usr/bin/php5?That's a common location for PHP 5.
|
I am using 1and1 hosting and trying to run a cronjob using PHP5. For some reason, the cron is using PHP4.. even though the global PHP version on site is PHP5.The script works fine in a browser, but gives me errors when SSHing and directly running the file. The reason I know it's using PHP4 is because it says "X-Powered-By: PHP/4.4.9"The cron looks like this:* * * * * /usr/bin/php /path/to/file.phpI'm thinking it's gotta be something related to the php path. Any ideas?
|
Getting cronjob to run PHP script as PHP5
|
I'm assuming you meant "every second day (every other day), as long as it's MON-FRI".According toQuartz CronTrigger Tutorial:'1/3' in the day-of-month field means "fire every 3 days starting on
the first day of the month".So,1/2would mean "fire every second day starting on the first day of the month". A cronExpression like0 0 12 1/2 * MON-FRI *should then be close to what you want. Checking withorg.quartz.CronExpression.isValidExpression("0 0 12 1/2 * MON-FRI *")...says that the expression is valid.However, testing it a little further with:CronExpression e = new CronExpression("0 0 12 1/2 * MON-FRI *");
e.isSatisfiedBy(new DateTime(2012, 9, 26, 12, 0, 0, 0).toDate());...throws an exception:> Exception in thread "main" java.lang.UnsupportedOperationException:
> Support for specifying both a day-of-week AND a day-of-month parameter
> is not implemented.So,seems likejhouse is rightand you just can't do that with a cronExpression.Maybe something like this would work as a workaround:Quartz cron expression for cron triggers executed every Nth Hour/Day/Week/Month
|
I don't know if the below expression is correct:<property name="cronExpression" value="0 0 12 2 * MON-FRI ?"/>I try to configure my trigger to fire every second day of every month, no matter the year, at noon, and the day of week has to be between Monday and Friday.I'd really appreciate if someone could help me. Thanks in advance.
|
Is this cronExpression correct?
|
I just experienced this. Problem for me was that the instances of rake and ruby I use were built locally, and installed to /usr/local/bin. There are other versions in /usr/bin (must check what I installed using apt-get in the past..).So, in my crontab file I set the path usingPATH=/usr/local/bin:/usr/bin:/bin(I was seeing it as PATH=/usr/bin:/bin in the failed crontab emails)and it works.
|
I'm running a crontab that executes a rake task. I'm getting the following error (with MAILTO from crontab):rake aborted!
no such file to load -- bundler
/Users/Mendel/Sites/misnooit/Rakefile:4
(See full trace by running task with --trace)I'm using rvm with:ruby: ruby 1.9.1p378rails: Rails 3.0.0.beta$GEM_HOME: /Users/Mendel/.rvm/gems/ruby-1.9.1-p378bundler: bundler (0.9.11)The error is pretty self explanatory but I'm not able to fix it.. Is there someone with more knowledge about this matter? Thanks in advance.
|
Crontab + rails3 + bundler
|
The easiest way might be to make use of thecronmethod so in your case$schedule->command('send:reminders')->cron('0 0 23 * *');That is saying run at midnight on the 23rd day of the month.
|
Now reading through thedocsI don't see a direct function for that, but I do see the option to use themonthly()method combined with awhen()method, so I thought, could I do this maybe:$schedule->command('send:reminders')->monthly()->when(function() {
return date('d') == '23';
});But now I'm afraid that won't work, because as far as I can see it will try thewhen()constraint only once a month (probably not on the date that I want it to) and then when it fails it skips that month. At least that's what I'm guessing from reading the source of laravel.So then I'm lost, how do I make this happen?
|
How can I schedule a laravel task on a specific day of the month?
|
You need to define a log file, which will then receive any output from yourPart.check_status_updatecall (such asputscalls). You can set a default log file for all of your jobs at the top of yourschedule.rbfile, such as:set :output, '/path/to/file.log'For example, to log toRails.root/log/whenever.log:set :output, 'log/whenever.log'You can also define the output per-task:runner "Part.check_status_update", :output => 'log/check_status_update.log'Seethe Whenever wiki entry on the subjectfor a full explanation of details and options, such as logging errors to a separate file.
|
I've got the following configuration. I've installed whenever gem, created shedule.rb:# Learn more: http://github.com/javan/whenever
every 6.hours do
runner "Part.check_status_update"
endIn part.rb model I have corresponding method.A.How can I check ifwheneverruns? As I understand it should only modify the crontab afterwhenevercommand in the bash, yes?B.If the method is not triggered - then how can I debug the scheduled jobs? If I put into my methodputsstatements - where shall they be stored or outputted?
|
How to check if whenever gem is working?
|
I could find the answer based on the comment by mu is too short.I modified the crontab to include the environmental variable NODE_PATH3,18,33,48, * * * * export NODE_PATH=/usr/local/lib/node_modules/ && /usr/local/bin/node /home/olmo/project/processDrivesMultiUser.jsnow I'm able to use modules innode.jsif called bycron.
|
I have the module underscore installed globally with npm. if I run the script/usr/local/bin/node /home/olmo/project/processDrivesMultiUser.jsit will run ok wherever I am on the path, but if I run a cronjob like this:3,18,33,48, * * * * /usr/local/bin/node /home/olmo/project/processDrivesMultiUser.jsI get this error:Date: Wed, 10 Sep 2014 16:26:01 -0600
From: Cron Daemon <[email protected]>
To:[email protected]Subject: Cron <olmo@db> /usr/local/bin/node /home/olmo/project/processDrivesMultiUser.js
module.js:340
throw err;
^
Error: Cannot find module 'underscore'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/home/olmo/sandbox/api_ievwebapp/parseAdminScripts/processDrivesMultiUser.js:20:9)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)somehow it can't find the moduleunderscoreif it runs via cron. I made the cron entry for the same username I'm using to run the script manually.any ideas?
|
can't import modules into a node script if it runs from cron
|
I supposecronuses theshshell to run your commands by default.shdoes not support curly-brace wildcards.IIRC, you can add to your crontab the following line:SHELL=/bin/bash
|
I was recently running a cron job using crontab -e and I found some strange behaviour. The following command doesn't work:* * * * * cp /home/username/{*txt,*pdf} /home/username/test/but the following does* * * * * cp /home/username/*txt /home/username/test/while both commands work in bash.Why am I not able to use curly brackets in cron?
|
Why can't I use curly brackets in crontab?
|
Activate cron jobs in Raspbmc
Per default running cron jobs is deactivated in Raspbmc and there are two ways to activate them.
- In the Raspbmc GUI under Programs -> Raspbmc Settings -> System Configuration -> Service Management -> Cronjob Scheduler
- Via SSH/FTP by modifying sys.service.cron value to “true” the settings file under /home//.xbmc/userdata/addon_data/script.raspbmc.settings/settings.xml
|
I have attempted adding cronjobs via SSH at /etc/crontab and also crontab -e. Neither one seems to work at all!
|
Raspberry Pi (RaspBMC) cronjobs not working
|
The percent (%) symbol is a special character in cron. Escape the % signs.0 0-23/2 * * * /tmp/sample.sh > /tmp/logfile_extract_$(date '+\%Y-\%m-\%d-\%H').txt 2>&1
|
I put a job in crontab to run every 2 hours, also i want the log file of my bash output in a separate file.Input:0 0-23/2 * * * /tmp/sample.sh | tee /tmp/logfile_extract_$(date '+%Y-%m-%d-%H').txtOutput:/bin/sh: -c: line 0: unexpected EOF while looking for matching `''
/bin/sh: -c: line 1: syntax error: unexpected end of file
|
How to use tee command in the crontab
|
Yes, you miss something ("runcrons" is not background deamon). From documentation:"Now everytime you run the management command python manage.py
runcrons all the crons will runif required. Depending on the
application the management command can be called from the Unix crontab
as often as required. Every 5 minutes usually works for most of my
applications."That means you have to put "runcrons" command in your crontab.Example:You have some CronJob that do something every 30 min.To get this running you must edit youcrontab(linux, mac) ortask scheduler(windows) to run "python manage.py runcrons" for every, let say 1 min.If you get this running, your CronJob will be pinged every 1 min and run if necessary (every 30 min or whatever value you have set).Hope this helps.
|
I got exact same problem described in thispost, but the answer doesn't help at all. In short, I am usingTivix django-cron, the cron job is not running at regular basis.To illustrate the problem, the following cron job class is intended to send email every min once runningruncronscommand. But in fact, it only sends out one email and no more. That defeats the purpose of cron... What am I missing?class TestCron(CronJobBase):
schedule = Schedule(run_every_mins=1)
code = 'test_cron_philip'
def do(self):
send_mail('cron test', 'body is test body', '[email protected]',
['[email protected]'],fail_silently=False)
|
How to use Tivix django-cron app
|
Yes. look at the "request" module for node.js. It is basically an http client which you can use from inside your node.js app. Seehttps://github.com/mikeal/request
|
What I am trying to achieve is to create script which will read from URL and then use this data to do some manipulations.In example. This script will run every 5 minutes, load page from somewhere, check if something changed, and if something did change (there is one small particular change I am actually will be looking for, but it doesn't matter, as the idea stays the same), it will send me an alert by email.
Question is. Can Node.js handle that?I can create this script in ruby, or even as shell script, run from crontab on server every N minutes; but I wanted to try out Node.js, and it sounds like I have a good "pet project" to try it on.
|
Is node.js capable of reading from URL?
|
It looks like you can use the alternate form offlock,flock <fd>, where<fd>is a file descriptor. If you put this into a subshell, and redirect that file descriptor to your lock file, then flock will wait until it can write to that file (or error out if it can't open it immediately and you've passed-n). You can then do everything in your subshell, including testing the return value of scripts you run:(
if flock -n 200
then
myscript.sh
echo $?
fi
) 200>lockfile
|
Greetings all. I'm setting up a cron job to execute a bash script, and I'm worried that the next one may start before the previous one ends. A little googling reveals that a popular way to address this is theflockcommand, used in the following manner:flock -n lockfile myscript.sh
if [ $? -eq 1 ]; then
echo "Previous script is still running! Can't execute!"
fiThis works great. However, what do I do if I want to check the exit code ofmyscript.sh? Whatever exit code it returns will be overwritten byflock's, so I have no way of knowing if it executed successfully or not.
|
How do I check the exit code of a command executed by flock?
|
The first is correct - it runs at 17:00 each day. The second runsevery17 hours. So 17:00 the first day, 10am the next and so on.
You can test your cron configurations athttps://crontab.guru/. Other similar sites are available.
|
I want to run a cron job at 17:00 everyday. Which one is the correct format?0 17 * * *or0 */17 * * *or are they both same? Please do tell the difference.
|
Cron job for everyday at 5pm
|
Setting a cron job to execute that frequently is not possible, and for good reason - a task executing that frequently shouldn't be done using a cron.Instead, you can use Timers with Node.js:function myFunc(arg) {
console.log("Argument received: " + arg);
}
setTimeout(myFunc, 500, "some message"); // Executes every 500ms.Timers can also be instantiated into a variable:const timeoutObject = setTimeout(() => {
console.log("I will print every 500ms!");
}, 500);
clearTimeout(timeoutObject);
|
I want to trigger a JavaScript function every 500ms using node cron jobs, though I couldn't find a way to make the cron execute any lower than a 1 second interval.cron.schedule("*/1 * * * * *", function() {
console.log("running a task every 1 second");
});Is there any way to run a function every 500ms using node cron jobs?
|
Is there any way to get milliseconds in CronJobs?
|
I've been maintaining a daily schedule .Manually triggering a DAG does not impact the scheduled triggering of the Airflow DAGs. It will continue to run as per schedule .
|
I want to use airflow DAG to run some jobs. I have scheduled the expression to every 25 mins, like*/25 * * * *. for instance, it seems to run, like at 6:25, 6:50, and at 7 as well, but I want to run it at 7:15, not at 7.as an alternative, I want to know, if I manually trigger a DAG, will the next trigger be affected by this, like will the next trigger be delayed, or will it continue on its own schedule.The airflowversionI am using is1.10.4
|
does manual triggering of a airflow DAG interfere with the scheduled airflow trigger?
|
When automating git tasks using SSH keys is recommended. You can setup SSH keys with push access by following these steps:get the SSH key of the user(or generate one:ssh-keygen -t rsa -b 4096 -C "[email protected]")copy contents of the public key (cat ~/.ssh/id_rsa.pub)Go to the project on github.comGo to project settingsChooseDeploy Keys(https://github.com/user/project/settings/keys)Choose add deploy keyAdd your public key contentsCheckAllow write accessChooseAdd KeyPlease note this will only work for repositories cloned with the following remote:[email protected]:user/project.gitThe remote can be updated wit the following steps:go to the repository folder on the serverrungit remote remove originrungit remote add origin[email protected]/project.git
|
Hey I am trying to push code to git using a cron job on the Mac. I edit my crontab usingcrontab -eand have the following inside:* 12 * * 1 ~/Dropbox/MD/sync.sh
* 12 * * 5 ~/Dropbox/MD/sync.shThe script is as follows:#!/bin/bash
cd ~/Dropbox/MD
/usr/bin/git add .
/usr/bin/git commit -m "Docs auto update"
/usr/bin/git push origin masterHowever the command fails and when I runmailI can check the error message which is:fatal: could not read Username for 'https://github.com': Device not configured. How can I fix this issue? If I run the commands manually from the terminal I have no issues and I am not prompted for user credentials.Any pointers on this would be much appreciated. Thanks!
|
fatal: could not read Username When pushing to git using a cron job
|
To combine the tips given here, this is how it worked for me:import os
CRONJOBS = [
('* * * * *', 'myapp.cron.test_cron_run', '>> ' + os.path.join(BASE_DIR,'log/debug7.log' + ' 2>&1 '))
]Additional notesThe directory needs to exist and you need write permissionAfter each change of CRONJOBS, runpython3 manage.py crontab addtwiceWithout the2>&1, error messages from python are not logged as they are written to STDERRCheck what is actually written to your crontab withcrontab -lIf it is not working, you may have a mail from cron. Depending on your system, read it withmail.
|
I have setup a cron job by using django crontab. As per defined in documentation I defined a test job in cron.py and defined it to run in 1 minute interval in settings.py.#cron.py
def test_cron_run():
print("\n\nHello World....!! ",timezone.now())
#settings.py
INSTALLED_APPS = [
'material.theme.cyan',
'material',
'material.admin',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
'django_crontab',
]
CRONJOBS = [
('*/1 * * * *', 'myapp.cron.test_cron_run','>>'+os.path.join(BASE_DIR,'log/debug7.log')),
]I have added the cron jobs by runningpython3 manage.py crontab add.
Also the job is added as I can see if I run,python3 manage.py crontab showHowever I cannot see any log file being generated.
Is there any way to debug this, the os logs or something?
|
How to debud django crontab?
|
Deleting all the schedule files in storage/framework did this job.The problem was the command was executed but was some error so never worked but the command was active preventing it to run again by the cron (because i used withoutOverlapping() ).
|
The below is the schedule functionprotected function schedule(Schedule $schedule)
{
$schedule->command('queue:work')
->everyMinute()
->withoutOverlapping();
}Below is the cron for laravel* * * * * /usr/local/bin/php /home/space/public_html/project/artisan schedule:run >> /home/space/public_html/project/public/op.txt 2>&1But each time the cron outputsNo scheduled commands are ready to run.queue:work is not getting executed, what am I doing wrong?
|
Laravel 5.3 Schedule Not working ( No scheduled commands are ready to run. )
|
*/15 0-2,8-23 * * * test.sh
─┬── ───┬──── ┬ ┬ ┬
│ │ │ │ │
│ │ │ │ │
│ │ │ │ └───── day of week (all)
│ │ │ └─────── month (all)
│ │ └───────── day of month (all)
│ └─────────────── hour (between 0-2 and between 8-23)
└────────────────────── min (every 15 minutes)Run every 15 minutes, from 12:00am to 02:45am and from 08:00am to 23:45 of every day.0-2,8-23is equivalent to0,1,2,8,9,10,...,23while*/15is equivalent to0,15,30,45.The above will not include 03:00, because the last execution would be 02:45; if we use 0-3 instead of 0-2, it would have also executed at 03:15,30,45.To be able to include also 03:00,(02:59 actually) we need to be a bit more verbose:14,29,44,59 0-2,8-23 * * * test.sh
|
My job requirement is:
1.Every 15 minutes
2.Everyday morning 8:00am tonext day03:00amSo the job keeps runs every 15 min from 08:00 am to next day 03:00 am.Can this be achieved using a cron expression.Tried this but it does not seem to help.0 0/15 8-3 * * ?Thanks,
Wajid
|
Cron expression that spans across next day
|
As the cronjob area says, you need to redirect the command’s output to/dev/null.Your command should look like this:wget -O /dev/null -o /dev/null "http://example.com/wp-admin/wp-mail.php" &> /dev/nullThe-Ooption makes sure that the fetched content is sent to/dev/null.If you want the fetched content to be downloaded in the server filesystem, you can use this option to specify the path to the desired file.The-ooption logs to/dev/nullinstead ofstderr&> /dev/nullis another way yo redirect stdout output to/dev/null.NOTESFor more information onwget, check themanpages: you can typeman wgeton the console, or use the online man pages:http://man.he.net/?topic=wget§ion=allWith both-Oand-opointing to/dev/null, the output redirection ( &> ... ) should not be needed.If you don't need to download the contents, and only need the server to process the request, you can simply use the--spiderargument
|
Im using godaddy as a webhost and id like to disable the email notification that is sent after a cronjob is done. Lucky for me they have been no help but the cronjob area says:You can have cron send an email every time it runs a command. If you do not want an email to be sent for an individual cron job you can redirect the command’s output to /dev/null like this:mycommand >/dev/null 2>&1Ive tried several variations of this and nothing seems to fix it.My command:wget http://example.com/wp-admin/tools.php?page=post-by-email&tab=log&check_mail=1Any advice is greatly appreciated.
|
Using WGET to run a cronjob PHP disable notification email
|
Here's how I am eval'ing my own cron hook.1) Find the appropriatehook_croncall in your module.modulename_cronis what you want.2) Figure out if any specific variables impact when it is run. In my case, there is a variablemodulename_cron_lastwhich tracks the last time the cron was run. I have to force this to 0 to get it to run.3) Run drush:drush eval "variable_set('modulename_cron_last', 0);"
drush eval "modulename_cron();"
drush eval "variable_set('modulename_cron_last', time());"ORIf you use the 2.x DEV version for D7 this is possibile with command:drush elysia-cron run [JOB_NAME]
or:
drush elysia-cron run [JOB_NAME] --ignore-time(use --ignore-time to force execution)4) Make a script and add it to your scheduler (in my case, the actual local Linux crontab)
|
Is it possible to run individual cron jobs via Drush? e.g. I have a cron job named "mycron". In the Esysia UI I can run that 1 job by clicking [run].In drush, I can use the command "drush elysia-cron" but that will run all active cron jobs.My Question: how can I run mycron (only) via drush?Request: Make all cron jobs available in drush so "drush elysia-cron mycron" would work.
|
Run individual cron jobs with Drush
|
Try to print out environment variables from a dummy job* * * * * env > /tmp/env.outputas suggested inhttps://askubuntu.com/questions/23009/reasons-why-crontab-does-not-workAlso check what shell crontab is using. You can set the$SHELLenvironment variable tobashby adding a lineSHELL=/bin/bashat the beginning of the crontab file.
|
I have a Python driver and library scripts that are siblings:/home/mydir/pythonProjs/driver.pylib.pyIndriver.pyI have the line:from lib import method1The following is successful from my command line on Linux:python /home/mydir/pythonProjs/driver.pyBut when I try the following in crontab:10 1 * * * export PYTHONPATH=~/mydir/pythonProjs; python /home/mydir/pythonProjs/driver.pyI get the error:ImportError: No module named lib.method1I have also attempted changing path setting in my crontab command to the fully-qualified path/home/mydir/pythonProjs, omitting the 'export', and have also attempted writing .sh files (with the necessary #!bin/bash...)I have one main question and a follow-up question:
main: What is a best practice way to fix my problem?
follow-up: What is the philosophy behind cron having different path access than my shell?Before I get down voted too quickly, I will mention that I have read but have not been successful (or correctly parsed) the following:
-Where can I set environment variables that crontab will use?-Crontab Issues running Python-http://pythonadventures.wordpress.com/2012/03/31/calling-a-python-script-from-crontab/
|
python crontab and paths
|
Had this exact same issue the other day, you probably just need to cd in to the directory where Artisan is located first. Try the following:* * * * * cd /var/www/huge/ && /usr/bin/php artisan queue:listenAlso, are you sure the currently in use PHP CLI is located at /usr/bin and not /usr/local/bin?If the above doesn't work try:* * * * * cd /var/www/huge/ && /usr/local/bin/php artisan queue:listen
|
I have got a page which queues up emails in beanstalked.The script works as intended, the emails get fired when i have a queue listener, ie.php artisan queue:listenBut when i remove the listener and add it to the crob job* * * * * /usr/bin/php /var/www/huge/artisan queue:listenThe emails don't get fired.
Any ideas?
|
Laravel artisan cron not working
|
As there is not a pattern that can match the three times, it is not possible to schedule that just with one crontab expression. You will have to use three:45 21 * * * python backup.py
31 16 * * * python backup.py
35 1 * * * python backup.pyNote also thatpython backup.pywill probably not work. You have to define full path for both files and binaries:35 1 * * * /usr/bin/python /your/dir/backup.pyWhere/usr/bin/pythonor similar can be obtained withwhich python.
|
I want to make crontab where script occurs at different minutes for each hour like this35 1,8,12,15,31 16,18,21 * * 0,1,2,3,4,5,6 python backup.pyI want script to run at16hour and 31 minutesbut it is giving me error bad houri want the cron occur at1:35am, then16:31, then21:45
|
How can make cron job which happen at different hours and minutes
|
This documentsuggest that if you're specifying 7 elements, the last needs to be a year or year range. The year field is marked as optional, and consequently doesn't seem to be specifiable as a wildcard.
|
I'm trying to use quartz_jobs.xml to schedule all my jobs, but the following XML results in an error:The cron-expression element is invalid. The value '0 0 23 1/1 * ? *' is invalid according to its datatype.Here's the XML:<?xml version="1.0" encoding="utf-8" ?>
<job-scheduling-data xmlns="http://www.quartz-scheduler.org/xml/JobSchedulingData"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.quartz-scheduler.org/xml/JobSchedulingData http://www.quartz-scheduler.org/xml/job_scheduling_data_1_8.xsd"
version="1.8">
<schedule>
<job>
<name>AUI</name>
<group>Group1</group>
<description>Archive Unpublished Incidents</description>
<job-class>ArchiveUnpublishedIncidents</job-class>
</job>
<trigger>
<cron>
<name>AUITrigger</name>
<group>TriggerGroup1</group>
<job-name>AUI</job-name>
<job-group>Group1</job-group>
<!-- trigger every night at 11 pm -->
<cron-expression>0 0 23 1/1 * ? *</cron-expression>
</cron>
</trigger>
</schedule>
</job-scheduling-data>What is wrong with that cron expression?
|
The cron-expression element is invalid
|
The Magento cron process runs under the UTC timezone.This can be verified by temporarily adding a small log statement to the cron observer.The method is:Mage_Cron_Model_Observer::dispatch()Look for this code in the first few lines:$now = time();Either right before or after, add this:Mage::log("cron timezone: " . date_default_timezone_get(), Zend_Log::DEBUG);Then check your var/log/system.log file and you will see that PHP/Magento is using the UTC timezone.
|
Im trying to figure out if my module cron is running at the correct time.The cron for my module is set at 1am (0 1 * * *), the time zone of the default store is Western Europe (Paris, Berlin etc GMT +2), the server time is EDT (Eastern Daylight Time).So on which time zone is the 1am schedule based on?Thanks,
|
Magento Cron Tab Job Time zone
|
Try this cron scheduler expression to effectively disable it: 0 0 0 1 1 ? 2099
|
I have application with configured cron tasks. Tasks scheduler config is separated to distinct file.Could I use same crone scheduler config to enable or disable any task by providing specific pattern?PS. I got different parse exceptions whet trying to use values like -1, 2000, 2810 for year in the pattern. It works for year 2080, but is there any common approach to be used here?Thanks.
|
Cron scheduler "disable pattern"
|
There are two types of solutions: First you can do what Randal Schwartz suggestedhere. Second you could use a Message Queue likeBeanstalkorGearman. Beanstalk has a Perl Client and is now persistent and is ideal for lightweight stuff. Gearman on the other hand has more features, more worked on. There is alsoTheSchwartz- use it if you can do without too much documentation.cronis ideal for systematically repeating tasks. For the kind of application you have, it appears thatSchedule::Atmight be more appropriate if you prefer a more generic "message-queue"Also see an old StackOverflow Threadhere
|
I have an apache2 / mod_perl website. On one page, I need to do some server/server communication via SOAP.The results of this communication are not required for the rendering of the page (but user input is required to trigger this communication).The SOAP communication is very slow.So what I want to do is process and print the page for the user, then do all the SOAP stuff behind the scenes.What's the best way to achieve this? start some fork? write the job to a file and have a cronjob pick it up?Thanks
|
How can I defer processing during apache / mod_perl page rendering?
|
crontab -l dumps your crontab to standard output, which you could redirect to a file. You could have a job (in cron, naturally) to redirect this to a file which is then diffed, and pushed to source control as necessary.
|
I've got a few dozen Linux machines runningcronand I'd like to put the crontabs in some sort of revision control system. For source control I use Mercurial (hg), so that'd be ideal, but if there's some other system that is better suited to this task I'd consider it.One aspect which is specific to my situation is that all the crontabs belong to a common user (not a real person, but a placeholder "services" login). I'd like the revision history to include the actual author of each change, rather than the special account where the cron jobs actually run.
|
Crontab revision control?
|
You should first run:whereis dockerMine is:/usr/bin/dockerThen modify crontab file as below:* * * * * /usr/bin/docker -v >> /root/cron.logYou also can change crontab file like this (above your crontab commands):SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/binThe complete sample in your case:SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
* * * * * docker -v >> /root/cron.log
|
On my server (QNAP) I can run docker:$ docker -v
Docker version 20.10.11-qnap6, build 90a753cIf I want to run the same docker command in a crontab$ sudo crontab -e
* * * * * docker -v >> /root/cron.logI do get the error log/bin/bash: docker: command not foundI do not understand why docker cannot be used as a crontab job, but it works, if I run it directly.
|
docker: command not found if called in a cronjob
|
Try using__DIR__ . "/myText.txt"as filename.http://php.net/manual/en/language.constants.predefined.php
|
$content = "some text here";
$fp = fopen("myText.txt","w");
fwrite($fp,$content);
fclose($fp);The above code creates a file in the folder where the PHP script is present. However when the script is called by Cpanel Cron then file is created in home directory.I want file to be created in the same folder where the php script is present even if its run by cron.How to do that ?
|
PHP create file in same directory as script
|
CURLcurl is a tool to transfer data from or to a server, using one of the
supported protocolssytax iscurl [oprions] URLThe URL syntax is protocol-dependent. You'll find a detailed descrip‐
tion in RFC 3986.similar is the case with wgetwget [options] URLBoth will submit request to weserver's php module via HTTP , which inturn calls php complier only . for them to use in cron cron.php must be in such location that can be requested via HTTPlike0 0 * * * /usr/bin/curl http://web-url/cron.php
0 0 * * * /usr/bin/wget http://web-url/cron.phpwhile0 0 * * * /usr/bin/php5.5 /website/cron.phpcan be used simply to run a php script local avaiable on servrer
|
I am trying to create a cronjob and I don't know what is the difference between those lines, ans which one I am supposed to use to make the Cronjob work correctly.0 0 * * * /usr/bin/php5.5 /website/cron.php
0 0 * * * /usr/bin/curl /website/cron.php
0 0 * * * /usr/bin/wget /website/cron.phpNow I need to know which one works, I am sure that my server has the CURL and WGET installed by using the commande line:whereis wget
whereis curlBut when I tried creating a simple php file to send me emails only this code worked for me:0 0 * * * /usr/bin/php5.5 /website/cron.phpSo what to do?
|
What is the differance between CURL, WGET and PHP Cronjob
|
I found out the way after some research,s = Booking.objects.all().filter(
created_at__range=[datetime.now() - timedelta(minutes=60), datetime.now()]
)Django provides a functionality to provide range in queries, using variablename__range.
|
This question already has answers here:How do I filter query objects by date range in Django?(8 answers)Closed8 years ago.I am trying to query my postgres database from django, I'm running a cron using custom management commands. I have a time stamped model calledBooking, which has created at and modified at parameters, so that I know if the cron job has already been called for that particular booking. Now the cron job is called every hour, So what I need to do is to query my Booking model ass = Booking.objects.all().filter(created_at = datetime.now())is there a way I can specify a time range for created_at rather than a specific value, I want my range to be current time - 1 hour to current time.I know that I can retrieve all objects and test all of them individually, I just wanted to know if there's a way to incorporate this into the Django query.
|
Specify time interval in Django TimeStampedModel while Querying [duplicate]
|
You can contact with your hosting server but temporary solution for this kind of problem is to use cronjob service there are lot of free cronjob service out there in web. you can try those service .I used this kind of service while creating a DDoS bot .. :p ..You can use these cronjob service but there are more ...https://www.setcronjob.com/https://www.easycron.com/search in google with "Cron job service" you'll find thousands of service like thisHappy coding :)
|
I am using the simple_html_dom script to parse a value from a website.My code:<?php
include('simpleparser/simple_html_dom.php');
$html = file_get_html('http://www.example.com');
foreach($html->find('strong') as $e) // the tag that I am fetching
echo $e->innertext ;
?>Now, I'd like to run this only once per day as the data, I am parsing updates only once every day.I've read a couple of articles about the cron task, but can not get it to work. The examples seem to overcomplicate things and are not relevant to my case.
My hosting plan has the cron scheduler disabled and no shell access and I don't know how else to set it up.
|
PHP simple parser to run only once a day
|
The version of cron running on Ubuntu 14.04 has no support forCRON_TZ. If you look atman 5 crontablocally on the Ubuntu box, you will see that the inability to change cron's timezone for scheduling purposes is called out as a limitation:LIMITATIONSThe cron daemon runs with a defined timezone. It currently does not support per-user timezones. All the tasks: system's and
user's will be run based on the configured timezone. Even if a user specifies the TZ environment variable in his crontab this
will affect only the commands executed in the crontab, not the execution of the crontab tasks themselves.So: you have to find out what time zone cron is using, and use that in your crontab. You can do this automatically if you have a script generating the crontab. For example:TZ=$(</etc/timezone) date +'%M %H' -d @$(date -ud '21:02' +%s)On my system,/etc/timezonecontainsAmerica/New_York, so the above command outputs02 17for what I should put in the first two fields of a crontab entry to get a job to run at 21:02 UTC. On your system, that file presumably containsEurope/Moscow, so the command would output02 00instead.
|
I need to run a cronjob at 21:02 GMT. My crontab is:CRON_TZ=GMT
02 21 * * * thecommandThis works well on SuSE, but does not work on Ubuntu. Instead, it runs thecommand at 20:02, i.e. the timezone is chosen as GMT+1. Why?The server timezone is MSK (now it is GMT+3).From man 8 cron :
"The daemon will use, if present, the definition from /etc/timezone for the timezone"$cat /etc/timezone
Europe/MoscowThe command lsb_release -a says:No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 14.04.1 LTS
Release: 14.04
Codename: trusty
|
which timezone does cron use on Ubuntu 14.04?
|
As pointed out in the comments already: Thecronis using a different shell than you do. You can set the shell to be used by cron via a variable at the top of yourcrontabto have the same result as in your terminal:SHELL=/bin/bashDetails can be found athttps://serverfault.com/a/678414
|
I am trying to run this comamand from bash script through crontab, it just gets SystemOut.log, though I expect to get SystemOut_* as well./app/hdup/get_logs SystemOut*But when i tried to run this above command from terminal, it worked properly and got both SystemOut.log and SystemOut_*Any idea what could have gone wrong?
|
wildcard character * does not expand in crontab, but runs from terminal
|
That script will give you a X11 authorization error when is set as cron job. To prevent this, just addexport DISPLAY=:0andexport XAUTHORITY=/home/username/.Xauthority(changeusernamewith your user name) in your script:#!/bin/bash
export DISPLAY=:0
export XAUTHORITY=/home/username/.Xauthority #change `username` with your user name
pcmanfm -w "$(find /home/likewise-open/MAPS/lucas.cardeal/Pictures/Wallpapers -type f | shuf -n1)"ADDENDUM: An update caused the above script to break in Lubuntu 16.04 and above. See this stackoverflow answerhttps://stackoverflow.com/a/46259031/5895207for the additional environment variable that needs to be specified in the script.
|
I made a simple bash script that changes the wallpaper for a random picture from my wallpapers directory using pcmanfm. It's something like that:#!/bin/bash
pcmanfm -w "$(find /home/likewise-open/MAPS/lucas.cardeal/Pictures/Wallpapers -type f | shuf -n1)"I want that automatically, so u put the script on crontab. But it has no effect when its called by crontab. What's wrong with my script? How can I fix it?Thanks
|
Changing wallpaper using pcmanfm by crontab
|
You might want to have a look atsidetiqtoo.https://github.com/tobiassvn/sidetiqThe gem supports complex timing expressions via theice_cubegem.I personally found comfortable to have a gem that would integrate seemlessly with sidekiq.Something like that should work:class TaskWorker
include Sidekiq::Worker
include Sidetiq::Schedulable
recurrence do
daily.hour_of_day(0).minute_of_hour(1)
end
def perform
# do magic
end
endCareful though when using this gem since there are some performance related issues with some time expressions.https://github.com/tobiassvn/sidetiq/wiki/Known-Issues. The expression I gave you should circumvent this issue though.
|
I have a Rails 3 app deployed heroku. I have a Sidekiq worker atapp/workers/task_worker.rb:class TaskWorker
include Sidekiq::Worker
def perform
...
end
endHow to schedule execution ofTaskWorker.perform_asyncdaily at 12:01 a.m?
|
Schedule background task with Sidekiq
|
There are a couple of things you can check, though more information is always more helpful (permissions and location of file, entire file contents, etc).It can never hurt to preface themysqldump.shfile with theShebang syntaxfor your environment. I would venture to guess#!/bin/bashwould be sufficient.Instead ofmysqldump -u ....use the absolute path/usr/bin/mysqldump(or where ever it is on your system). Absolute paths are always a good idea in any form of scripting since it's difficult to say if the user has the same environment as you do.As for storing the errors in dump.log, I don't believe your syntax is correct. I'm fairly sure you're piping the errors fromgzipinto dump.log, not the errors frommysqldump. This seems like afairly common questionwhich arrives at the answer ofmysqldump $PARAMS | gzip -c dump-$(date)
|
I'm trying to create a cron job for database backup.This is what I have so far:mysqldump.shmysqldump -u root -ptest --all-databases | gzip > "/db-backup/backup/backup-$(date)" 2> dump.log
echo "Finished mysqldump $(date)" >> dump.logCron job:32 18 * * * /db-backup/mysqldump.shThe problem I am having is the job is not executing through cron or when I am not in the directory.Can someone please advise. Are my paths incorrect?Also, the following line I'm not sure will output errors to the dump.log:mysqldump -u root -ptest --all-databases | gzip > "/db-backup/backup/backup-$(date)" 2> dump.logWhat worked:mysqldump -u root -ptest --all-databases | gzip > "../db-backup/backup/backup-$(date).sql.gz" 2> ../db-backup/dump.log
echo "Finished mysqldump $(date)" >> ../db-backup/dump.log
|
Creating a cron job for mysqldump
|
If you save the time when the ticket is to be unlocked and then when someone wants to book it you just have to see if that time has passed, it should work without any trouble or stress to the server.So in your ticket table you add adatetimefield named 'booked_until', store the time when the item is going to get unlocked and you are set!
|
I'm struggling to come up with a solution for events ticket booking system. I need some idea how to lock a ticket once added to 'a cart' so it cannot be booked by other customerHow is this done on other ticket booking sites where the ticket is reserved for eg 10 minutes and then gets released after that time when transaction is not completed. Running cron job every minute wouldn't be viable, would it?
|
Lock a ticket for an amount of time (events tickets booking system)
|
Here's the definition ofPID. A PID file is a file that contains a process identifier. If Tomcat's startup scripts are run withCATALINA_PIDenvironment variable set properly, then the PID of the Tomcat process will be recorded to a file upon startup. If the file exists when you try to start Tomcat, the scripts will refuse to run because it does not want to clobber a (possibly valid) PID file.If you are sure that Tomcat is not running, simply delete the file (it should be available through theCATALINA_PIDenvironment variable) and try again.I share @jordanm's comment about using exit codes instead of checking for specific (text) output: the latest version of Tomcat does not even use the messages that you have shown above, so it's very fragile.If you want a self-re-starting service, considering looking atjsvc, which actually ships with Tomcat binaries in source form.
|
I am making a shell script to restart tomcat after crash.
I wonder I need to handle this message in my script "Tomcat servlet engine is not running, but pid file exists."
What does this message means?
Do I need to take it into account as an error message that oblige me to restart Tomcat?My script is as follow:#!/bin/bash
SERVICE=/etc/init.d/tomcat7
STOPPED_MESSAGE=" * Tomcat servlet container is not running."
PID_FILE_MESSAGE=" * Tomcat servlet engine is not running, but pid file exists."
if [ "`$SERVICE status`" == "$STOPPED_MESSAGE" ];
then
{
$SERVICE start
}
else
if [ "`$SERVICE status`" == "$PID_FILE_MESSAGE" ];
then
{
$SERVICE restart
}
fi
fi
|
Tomcat servlet engine is not running, but pid file exists. What does this message mean? Do I need to recover Tomcat if I get it?
|
Why not write a mono-based exe that takes the DLL path and entry point method as parameters? The exe would then use reflection to load the DLL and execute the specified method. (You could opt for convention-over-configuration by specifying something like a DllMain method in your DLL which the exe would know to call automatically. Then just one parameter would be required and the intent of your code more obvious.)Implementing such an applet would give you a utility similar to RunDll in Windows and allow you to run mono DLLs from cron.
|
I was wondering if i can run a dll (c#) with crontab ? The dll is compile with mono.thx :)-- EDIT --Well it can be a .exe. I was looking at daemons on mac and linux, do you think I can run .exe as a daemon.
|
Run C# .exe with crontab or daemon?
|
If the input is read by the script fromstdin, just redirect input from a file (using a wrapper script).#! /bin/sh
test.sh < data.inIf this does not work for you (i.e. you have your script calling some interactive shell program like telnet, you can useExpectto automate the interaction.
|
i created a crontab which will run a bash script test.sh. This test.sh file requires some input from the user, and saves the user input into a variable. How do i ensure that the user input will be saved to a variable in test.sh, and when crontab runs the script i can get the output i want?for e.g i have 2 files, file1.sh and file2.sh. i put file2.sh in file 1.sh. i then run file1.sh, get the user input, and save it somewhere. crontab will run file2.sh, and retrieve the value from the "saved somewhere variable". is there anyway for this?
|
Run crontab with user input
|
You did not specify what you are doing in theAddCronJobmethod, but I guess you are doing aCronExpression.Parse("* * * * * *")method call somewhere, and this will throw the exception. To fix it you should change it toCronExpression.Parse("* * * * * *", CronFormat.IncludeSeconds)like it says on the github page what you linked:https://github.com/HangfireIO/Cronos#adding-seconds-to-an-expression
|
I am using the Cronos library to handle my cron jobs on .NET Core.However I have encountered this issue where the common Cron Expressions are not being parsed in at all. It keeps giving me a CronFormatException.I have looked through the Github page and used their formats but I still get the same Exceptions.This is my code:services.AddCronJob<Worker1>(x =>
{
x.TimeZoneInfo = TimeZoneInfo.Local;
x.CronExpression = "* * * * * *";
});I want to run it every second but I get the CronFormatException issue.This is the library:https://github.com/HangfireIO/CronosDoes this library use a different cron format?
|
.NET Core Cronos Cron Expressions not parsing correctly
|
If the first line of your #rstats script is wd <- here(), I will come
into your lab and SET YOUR COMPUTER ON FIRE.Learn how to use environment variableswd <- Sys.getenv("HOME")
wd <- file.path(wd, "projects", "my_proj")Or use the 'Additional arguments to Rscript' element in the cronR user interface to pass something extra to the Rscript and fetch it with commandArgs().
If you don't use the cronR interface but cron_rscript, usecronR::cron_rscript(..., rscript_args = "/home/pd/projects/my_proj")args <- commandArgs(trailingOnly = TRUE)
if(length(args) > 0){
wd <- args[1]
}
|
I've been using theherepackageto make my projects more portable. It works great apart from when I usecronRtoschedulesome of my scripts. When I runmy_script.Rfrom Rstudio I get a message fromlibrary(here):here() starts at /home/pd/projects/my_projWhen I setscript.Rto run usingcronRI get a different message:here() starts at /home/pdWhich is wheremy_schedule.cronis stored. Ideally I want to keepmy_schedule.cronwhere it is. I can see from the logs thatmy_script.Rruns fine apart from when it comes to saving data because the path used byhere()is incorrect. Is there anyway to get theherefunction to detect the project dir whenmy_script.Ris run fromcronRor the terminal?
|
Correct way to use here package with cronR scheduling
|
First of all, there's an article in the official documentation explaining how to write rc scripts:Practical rc.d scripting in BSD.It will probably answer most of your questions.When it comes to your script:The keywords likePROVIDE,REQUIRE, etc. have to be comments. See therc(8) manual pageand thercorder(8) manual pagefor more details.#!/bin/sh
#
# PROVIDE: test
# REQUIRE: LOGIN NETWORKINGI think you also miss settingtest_enableto a default value.: "${test_enable:="NO"}"You don't really want to just put the instructions to start your daemon in the global scope of the script. This part of your code is bad:cd /home/deploy/projects/test
/usr/sbin/daemon -u deploy /usr/local/bin/node /home/deploy/projects/test/server.jsYou should try to define astart_cmdfunction (look forargument_cmdin therc.subr(8) manual pagefor more information) or define thecommandvariable.All in all, the best idea is to look at other scripts in/etc/rc.dand/usr/local/etc/rc.dto see how people write those and what are the standards. This is how I've learnt it recently as I was developing a daemon for the Keybase filesystem (KBFS). You may look at the codehere.The manpages are also helpful. Start withrc(8)and then look at other manuals listed in theSEE ALSOsection.
|
I have a simple script:#!/bin/sh
PROVIDE: test
REQUIRE: LOGIN NETWORKING
. /etc/rc.subr
name="test"
load_rc_config $name
rcvar=test_enable
cd /home/deploy/projects/test
/usr/sbin/daemon -u deploy /usr/local/bin/node /home/deploy/projects/test/server.js
run_rc_command "$1"inside/usr/local/etc/rc.d. It is executable. It is registred into /etc/rc.confI need it to start after boot/reboot. I managed to do it with Cron using@rebootbut it doesn't look legit. What is the proper way to run that script automatically after boot/reboot?
|
Running a script in FreeBSD after boot/reboot
|
The pattern is a list of six single space-separated fields: representingsecond,minute,hour,day,month,weekday.Month and weekday names can be given as the first three letters of the English names.So a Monday in the first 7 days of the month should generate what you are after."0 0 12 1-7 * MON"https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/support/CronSequenceGenerator.html
|
Now I have the following declaration:@Scheduled(cron = "0 0 12 ? * MON#1")
protected synchronized void execute() {...}and it doesn't work:at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-1.5.9.RELEASE.jar:1.5.9.RELEASE]
Caused by: java.lang.IllegalStateException: Encountered invalid @Scheduled method 'execute': For input string: "2#1"
at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.processScheduled(ScheduledAnnotationBeanPostProcessor.java:461) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.postProcessAfterInitialization(ScheduledAnnotationBeanPostProcessor.java:331) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:423) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1633) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
... 19 common frames omittedPlease, help to make it working
|
How to fire the job on first monday of month using cron expresssion in spring @Scheduled?
|
So my question is, are there any efficient approach to process Queues? Is there any Symfony Bundle/Feature to do such specific task?You can takeenqueue-bundleplusdoctrine dbal transport.It already takes care of race conditions and other stuff.
|
I've an application in Symfony that needs to send Emails/Notificatios from the App.
Since the Email/Notifications sending process takes time, so I decided to put them in Queue and process the Queue periodically. Hence I can decrease the response time for the Requests involving the Email/Notification dispatch.The Cron Job(a php script - Symfony route) to process the queue runs every 30 seconds, and checks if there are any unsent Emails/Notifications if found it gets all data from the Queue Table and starts sending them. When an Email/Notification is sent, the Queue Table row status flag is updated to show that it's sent.Now, when there are more Emails in Queue which could take more than 30 seconds to send. Another Cron Job also start running and starts sending emails from the Queue. Hence resulting in duplicate Emails/Notifications dispatch.My Table structure for Email Queue is as follows :|-------------------------------------|
| id | email | body | status | sentat |
|-------------------------------------|My Ideas to resolve this issue are as follows :Set a flag in Database that a Cron Job is running, and no other Cron Jobs should proceed if found the flag set.Update status as 'sent' for all records and then start sending Emails/Notifications.So my question is, are there any efficient approach to process Queues? Is there any Symfony Bundle/Feature to do such specific task?
|
Handle Queue race condition in PHP Symfony with MySQL Database
|
runwhich phpto see where the php executable is, copy that path.crontab -e(I'm assuming this is your project root where your artisan is located/home/pofindia/public_html/beta-var1/but this requires you to add artisan to it, as so/home/pofindia/public_html/beta-var1/artisan)add the crontab entry* * * * * /usr/local/bin/php /home/pofindia/public_html/beta-var1/artisan Demo:Cronreally all you are doing here is providing the absolute paths
|
I have created an example schedule job to run after a specific time in Laravel 5.2. And this is working fine onlocalhostthroughartisancommand.I am running this command on local server:php artisan Demo:CronNow I am adding this task in cPanel's advance option cron job on HostGator hosting server. But it is not working.This is the command I am trying:cd /home/pofindia/public_html/beta-var1/ && /usr/local/bin/php artisan Demo:CronPhp version: 5.4 default.
And here is my example file<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use DB;
class DemoCron extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'demo:cron';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
DB::table('items')->insert(['name'=>'hello new']);
$this->info('Demo:Cron Cummand Run successfully!');
}
}
|
How to run laravel 5.2 artisan command on cron job on hostgator hosting server cpanel?
|
Assuming that after January 25th you want to run this process forever after (i.e. 2032, when probably the server will be already substituted), I would do it with three expressions:0 0 12 25-31 1 * 2016 command # Will run the last days of Jan 2016 after the 25th
0 0 12 * 2-12 * 2016 command # Will run the rest of the months of 2016
0 0 12 * * * 2017-2032 command # will run for every day of years 2017 and after.I hope this helps.
|
I need a cron expression which will fire every day at 12 pm starting from jan 25 2016. This is what I came up with:0 0 12 25/1 * ? *but after jan 31, the next firing time is feb 25.Is there a cron expression expression for doing this? If not what can I use?
|
Cron expression to run every day starting from a date
|
The problem is with the cron or script file itself: it has DOS line separators (CRLF) instead of Unix (LF only). You can fix it usingdos2unix.
|
When I pipe output to a file in a cron job using the > operator, it always appends a ^M to the end of the file name. This shows up as a ? when I run ls in the directory but reveals itself as ^M when I edit the file in nano and go to save.For example this command:locale > locale.txtOutputs a file named "locale.txt?" (i.e. "locale.txt^M")I don't know why it does this, but I'm guessing it has something to do with environment variables. When I use > from a terminal it behaves properly. I've searched Google for this problem but apparently it doesn't like all these special characters in the query so I haven't found anything.I've tried using mv to change the file name back to normal but it doesn't recognize the ? or the ^M character when I type in the file name.I've seen that perhaps this is the carriage return "\r" character but I don't know why cron would put a Windows newline on the end of my file name. All help is appreciated. Thanks!
|
Ubuntu 14.04 Cron outputs file names with ^M at the end
|
Try to moveadd_actionoutside of a function:function starthere(){
if (!wp_next_scheduled('my_hourly_event')) {
wp_schedule_event( time(), 'hourly', 'my_hourly_event' );
}
}
add_action( 'my_hourly_event', 'Download_CSV_with_args' );
function Download_CSV_with_args() {
wp_mail('[email protected]', 'Automatic email', 'Cron works!');
}
|
I'm trying to trigger cron job from WordPress Plugin that I'm writing (It's gonna take all new Products and export them to CSV every day) so the problem is that when I'm put this code in functions.php all working great and the code is valid but from the plugin folder it's scheduled and I can see it (with Cron View Plug-in) but not executed.. I found another same questions but there was no answer..
It seems like it's not really been triggered or something is blocking it..
take a look at my code..function csv_init(){
add_action('my_hourly_event', 'Download_CSV_with_args');
}
function starthere(){
// some code here
$file = $_SERVER['DOCUMENT_ROOT'].'/wp-content/csv_settings.php';
$content = serialize($args);
file_put_contents($file, $content);
wp_schedule_event( current_time( 'timestamp' ), 'hourly', 'my_hourly_event');
$schedule = wp_get_schedule( 'my_hourly_event' );
echo wp_next_scheduled( 'my_hourly_event' ).'<br>';
if ($schedule){
echo '<h3>The "'.$schedule.'" Cron Job is running..</h3>';
}else {
echo '<h3>There are no Cron Jobs that running..</h3>';
}
}
function Download_CSV_with_args() {
//execution of my code
}
|
wp_schedule_event hook scheduled but not working
|
Thecrontab -ecommand invokes your default editor, which is one of the following:The command specified by the$VISUALenvironment variable (if it's set); orThe command specified by$EDITOR; or/usr/bin/editorThe latter is a symbolic link tosomeeditor. On Linux, the default appears to benano.If it'snano, then there should be a 2-line menu at the bottom of the screen. TypeCtrl-Xto exit; if you've modified the file it will ask you whether you want to save it.If you have a preferred editor, you should set both$VISUALand$EDITORto the command used to invoke it. For example, I have:export EDITOR=vi
export VISUAL=$EDITORin my$HOME/.bash_profile.This applies to the system I'm using, a recent Linux system with the Vixie cron implementation. If your system differs significantly, not all of this is necessarily applicable.man crontabshould explain how thecrontabcommand works. If not, the documentation is alsoavailable here.(Incidentally, I keep my crontab in a separate file under my home directory, maintained in a source control system. That lets me keep track of changes and revert to a working version if I mess something up. Withcrontab -e, it's easy to make mistakes and difficult to recover from them.)
|
I open the file in terminal throughcrontab -ecommand and now I want to save it. I've tried several things, like:wqorCtrl-X, but it did not save the file. How can I do that?
|
How to save the file after typing "crontab -e"
|
I don't know how much versions of Cron expression exist but the most famous one is indeed the Unix one.If you want to translate a Unix Cron expression to a Quartz Cron expression consider this.Quartz format is :(second, minute, hour, day_of_month, month, day_of_week, year)Unix format is :(minute, hour, day_of_month, month, day_of_week, task)So if you to translate a Unix cron into Quartz, you just have to add a value for thesecondandyear.If you want the same cron, you use 0 forsecondand*foryear
|
I am a little confused about the Cron expression used in the unix system and the one Java Quartz is used.The left-most entry of standard cron expression used by Unix represents "minute". But the cron expression used by Quartz uses the left most entry to represent "second":http://quartz-scheduler.org/documentation/quartz-1.x/tutorials/crontriggerI want to know how many versions of cron expression are currently being used?What happens if I pass the standard version of cron into Quartz?Thanks a lot
|
Different types of Cron Expression
|
0 16 1 1/6 ? *CronMaker can help you in the future.http://www.cronmaker.com/
|
How to write cron expression to trigger a function on every 6 month at 16 pm in the evening?
|
Spring Cron expression to trigger at every 6 months
|
Repeatedly and recursively scratching the filesystem for garbage with find and fuser is generally a bad idea.Move away from storing sessions in files and you instantly get rid of this and a lot of other problems, if not already done. If you are actually not using file storage for sessions, just delete that line (or comment out).
|
We are seeing our server's CPU spike at 30 minute intervals. this is likely caused by php5 job to cleanup session files. this is taken from our /etc/cron.d/php5 on the server:# /etc/cron.d/php5: crontab fragment for php5
# This purges session files older than X, where X is defined in seconds
# as the largest value of session.gc_maxlifetime from all your php.ini
# files, or 24 minutes if not defined. See /usr/lib/php5/maxlifetime
# Look for and purge old sessions every 30 minutes
09,39 * * * * root [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 -maxdepth 1 -type f -ignore_readdir_race -cmin +$(/usr/lib/php5/maxlifetime) ! -execdir fuser -s {} 2>/dev/null \; -deletethere seems to have been a problem with this job in past releases. there was a problem in version 11.10 of Ubuntu with this taking high amounts of CPU but we are running much later builds of both Ubuntu and PHP.
how important is this job for PHP? can we stop this job from running or lower its priority?
|
fuser process php5 cron job using high amounts of cpu
|
Cron treats % as a special character (meaning "new line", hence the references to lines 0 and 1 in the error message). You need to escape it:date "+\%Y-\%m-\%d"By the way, the posix$( )syntax is generally better than backticks - it allows nested commands.
|
I am configuring Cron to backup my sql automatically. However I think that Cron has some issues and it's not working well.This is the command I am running:mysqldump --opt -Q -uhereisthename -p'hereisthepasswordwithstrangecharactersthatmustbeescaped' databasename | gzip > /home2/username/backups/backupnamefolder/backupdbwebsitename.`date +"%Y-%m-%d"`.gzWhen I run it via SSH it works fine and generates the backup.
However if I run it via Cron, I get the following error:/bin/sh: -c: line 0: unexpected EOF while looking for matching `''
/bin/sh: -c: line 1: syntax error: unexpected end of fileAnybody can suggest what's wrong?
|
Error on cron job, but working fine on shell
|
/user/bin/php -q "/path/Script.php" >> /path/LogFile.htmlthe-qswitch will run it in quiet mode which will disable header outputphp command line helpfor more switches
|
cron command:/user/bin/php "/path/Script.php" >> /path/LogFile.htmlwhen php outputs to my log file, it always starts off by sayingX-Powered-By: PHP/5.3.22 Content-type: text/htmlso with my output file, it looks something like:X-Powered-By: PHP/5.3.22 Content-type: text/html X-Powered-By: PHP/5.3.22 Content-type: text/html X-Powered-By: PHP/5.3.22 Content-type: text/html X-Powered-By: PHP/5.3.22 Content-type: text/html
NEW DAY MARKER | 29/04/2013 00:00:07
Total Exchanges: 73294
Total GMT references: 7
Exchanges pending approval: 4the output is in a table format, causing the the repeated text/html header to flood the first 4 or 5 pages of my log file - because they are between</tr> X-Powered-By: text/html <tr>tags.is there anyway i can tell it not to put out that kind of header information when running cron jobs? (i don't want to disable it globaly - need web interface to still work with other PHP scripts)linux host, cpanel, vps
|
cron php how to stop headers in append to file
|
As suggested in the comments, the problem might be that you and your crontab are using a different R install.To check if it is the case, runwhich Rscriptas yourself and as crontab.If they are different (which I suspect), you could use the full path to the appropriateRscriptwhen you are calling it from crontab. A more permanent solution would require setting environment variables.
|
I am having problems when trying to run my R script usingRscriptviacrontab.The following command works fine when running in the command lineRscript /var/www/html/sent/sentiment/code/parse.rBut the following line insidecrontab*/5 * * * * Rscript /var/www/html/sent/sentiment/code/parse.r > /var/www/html/sent/sentiment/code/backup.log 2>&1Will return the following error in the logError in library(twitteR) : there is no package called 'twitteR'
Execution haltedWhy is it possible that Rscript won't be able to find the packages when running using cron?
How can I make crontab 'see' my R packages.Any tip much appreciated.
|
R can't find some packages when running via crontab
|
I think it is much better to let your application control the frequency of events instead of the cronjob. Let the cronjob run a certain action of your application every minute. The action then for example checks a database table named cronjobs and runs the jobs marked for running by either a frequency number or a timestamp.If you do it like this, you can add new jobs programmatically from everywhere, e.g. via an cronjob interface.The solution is easier to maintain, to test and to document.
|
Can we configure cron job's time interval through PHP script, so that the time interval should not be set manually, but through a PHP script, whether it takes time interval from Database or fixed (but from within the PHP code).Thanks in advance
|
Can we configure cron job's time interval through PHP script?
|
Any language (in case of MySQL, any language with mySQL libraries) can be used as long as it has:Command line interface. Not sure which languages disualify - apparently even LOGO has CLI capable implementations now, though what use is LOGO in background program is somewhat beyond me :)Resulting code runs on whatever system your cron daemon is on (most usually, a Unix server, but I assume there are cron ports to Windows etc...)Any other considerations have nothing to do with cron jobs.Efficiency wise, it depends entirely on what the work done by the job is (but again, not really related to cron-ifying the job).With some extreme performance-intensive exceptions, choose the best language you can develop in (based on your familiarity with it and the availability of needed libraries).For performance sensitive code, the usual choice is C++ and/or Assembly for really optimized stuff - but to be honest the whole performance discussion is completely outside the scope of your question and I'm sure has plenty of perfectly-answered question on StackOverflow elsewhere.
|
I realize that it can depend on certain things (and obviously how efficient the code is written); but, in general, what is the most suitable and perhaps efficient language to use in writing cron jobs?Does this simply come down to a question of what is the most efficient language period, or can the specificity of cron jobs determine one programming language over the other?Also, does MySQL database operations affect the programming language of choice for cron jobs?
|
Suitable language for cron Jobs?
|
Is my Spring Cron expression configured, to run every Tuesday night at 9
wrong?Yes :)But try,0 0 21 ? * TUEOr with the Spring annotation:@Scheduled(cron = "0 0 21 * * TUE")The following is a really handy website for creating Cron expressions.http://www.cronmaker.com/Take note: Just remove the last element from the created expression to use it with Spring scheduling.And a nice way to verify it in Natural Languagehere
|
I am using Spring schedule. I configured the following Cron expression to run my task every Tuesday night at 9pm,"0 0 21 * * TUE"However, I am getting the following exception when am starting the applicationEncountered invalid @Scheduled method 'runSchduler': Cron expression must consist of 6 fieldsIs my Spring Cron expression wrong?
|
Spring Cron Expression to run every Tuesday night 9?
|
You cannot configure GAE cron services with resolutions below 1 minute. FWIW, you can't do that on unix/linux systems either.But it is possible to use anevery 1 minutescron job from which you can further trigger delayed execution of deferred/push/pull queue tasks with down to 1 second resolution, seeHigh frequency data refresh with Google App Engine
|
When setting up a Google App Engine instance you can configure acron.yamlto set up Cron jobs.There does not seem to be any documentation on how to configure jobs that run say every 30 seconds.I triedschedule: every 30 secondsandschedule: 0/30 0 0 ? * * *But no good. Google Cloud tells me the format is incorrect when I deploy. Can you schedule in frequencies less then 1 minute with Google App Engine Cron jobs?
|
Google App Engine - How to set up Cron job using seconds
|
Did you run the embedded scheduler? SeeRunning the Schedulersection inthe documentation:tab = CronTab(tabfile='MyScripts.tab')
for result in tab.run_scheduler():
print "This was printed to stdout by the process."Because windows doesn't have a crontab process, you have to either feed your crontabs into an existing daemon or use this run_scheduler within your process to create a daemon for yourself.
|
I want to schedule a python script using the python-crontab module on Windows platform. Found the following snippet to work around but having a hard time to configure. Script namecronTest.py:from crontab import CronTab
file_cron = CronTab(tabfile='filename.tab')
mem_cron = CronTab(tab="""
* * * * * command
""")Let's say, for example, I want to print date & time for ever 5 mins using the following script, nameddateTime.py:import datetime
with open('dateInfo.txt','a') as outFile:
outFile.write('\n' + str(datetime.datetime.now()))How do I executedateTime.pyand setup the cron job for every 5mins throughcronTest.py.
|
Scheduling Python script using Python CronTab on Windows 7
|
You could useorg.quartz.CronExpression.getNextValidTimeAfter(). Using this method you can iteratively get as many trigger times as you wish.You have to decide what will be the starting point of your iteration, will it be the current moment or epoch or smth else.And you can parse a string cron expression intoorg.quartz.CronExpressionusing constructorCronExpression(String cronExpression).EDIT:you can find a similar functionality in the Spring framework'sCronSequenceGenerator. Both could be used in the similar iterative fashion so you could check which one suits you the best regarding performance etc.
|
I was wondering what is the most efficient way/best library to parse a cron expression and return a list of time points in Java.For example I would have a cron expression, say,Fire every minute in October 2010and would get a list/array of epoch times (or some other date format) returned that correspond to the times the trigger fires.Thanks
|
Cron Expression To List of Dates/Timepoints
|
Make sure, that you execute the script as php script and not as bash script.Your crontab should look like this:* * * * * /usr/bin/php -f /path/to/file.phpAnother way to execute the script as php is to add a shebang in the first line:#!/usr/bin/php
<?php ...
|
Moved the site to another server. Add file statistic.php to the Сron to perform. Only this Cron that does not like something. Write errors:/home/site/www/statistic.php: line 1: ?php: No such file or directory
/home/site/www/statistic.php: line 2: syntax error near unexpected token `"bd.php"'
/home/site/www/statistic.php: line 2: `include ("bd.php");There is my code<?php
include ("bd.php");
$result = mysql_query("SELECT MAX(id) FROM statistic_dep",$db);
$myrow1 = mysql_fetch_array($result);
$last_id=$myrow1[0];
...
|
Cron syntax error near unexpected token
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.