Response
stringlengths 8
2k
| Instruction
stringlengths 18
2k
| Prompt
stringlengths 14
160
|
---|---|---|
A few crickets heard in this question. Good 'ol RTFC with some discrete event simulation papers and Wikipedia:
http://en.wikipedia.org/wiki/Cron#Multi-user_capability
The algorithm used by this cron is as
follows:
On start-up, look for a file named .crontab in the home directories of
all account holders.
For each crontab file found, determine the next time in the future
that each command is to be run.
Place those commands on the Franta-Maly event list with their
corresponding time and their "five
field" time specifier.
Enter main loop:
Examine the task entry at the head of the queue, compute how far in the
future it is to be run.
Sleep for that period of time.
On awakening and after verifying the correct time, execute the task at
the head of the queue (in background)
with the privileges of the user who
created it.
Determine the next time in the future to run this command and place
it back on the event list at that time
|
How do "modern" cron daemons internally schedule their jobs? Some cronds used to schedule a run every so often via at. So after a crontab is written out, does crond:
Parse the crontab for all future events and the sleep for the intervals?
Poll an aggregated crontab database every minute to determine if the current time matches the schedule pattern?
Other?
Thanks,
|
How does cron internally schedule jobs?
|
Your docker exec command says it needs "pseudo terminal and runs in interactive mode" (-it flags) while cron doesn't attach to any TTYs.
Try changing your docker exec command to this and see if that works?
docker exec mongodb mongodump -d meteor -o /dump/
|
I have pretty simple command which is working fine standalone as a command or bash script but not when I put it in crontab
40 05 * * * bash /root/scripts/direct.sh >> /root/cron.log
which has following line
PATH=$PATH:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
SHELL=/bin/sh PATH=/bin:/sbin:/usr/bin:/usr/sbin:/root/
# Mongo Backup
docker exec -it mongodb mongodump -d meteor -o /dump/
I tried to change the url of script to /usr/bin/scirpts/ no luck
I even tried to run script directly in cron
26 08 * * * docker exec -it mongodb mongodump -d meteor -o /dump/ >> /root/cron.log
with no luck, any help appreciated.
EDIT
I don't see any errors in /root/cron.log file either
|
docker exec is not working in cron
|
AWS announced support for scheduled functions in Lambda at its 2015 re:Invent conference. With this feature users can execute Lambda functions on a scheduled basis using a cron-like syntax. The Lambda docs show an example of using Python to perform scheduled events.
Currently, the minimum resolution that a scheduled lambda can run at is 1 minute (the same as cron, but not as fine grained as systemd timers).
The Lambder project helps to simplify the use of scheduled functions on Lambda.
λ Gordon's cron example has perhaps the simplest interface for deploying scheduled lambda functions.
Original answer, saved for posterity.
As Eric Hammond and others have stated, there is no native AWS service for scheduled tasks. There are only workarounds and half solutions as mentioned in other answers.
To recap the current options:
The single-instance autoscale group that starts and stops on a schedule, as described by Eric Hammond.
Using a Simple Workflow Service timer, which is not at all intuitive. This case study mentions that JPL used SWF to build a distributed cron, but there are no implementation details. There is also a reference to a code example buried in the SWF code samples.
Run it yourself using something like cronlock.
Use something like the Unreliable Town Clock (UTC) to run Lambda functions on a schedule. Remember that Lambda cannot currently access resources within a VPC
Hopefully a better solution will come along soon.
|
Currently I have a single server in amazon where I put all my cronjobs. I want to eliminate this single point of failure, and expose all my tasks as web services. I'd like to expose the services behind a VPC ELB to a few servers that will run the tasks when called.
Is there some service that Amazon (AWS) offers that can run a reoccurring job (really call a webservice) at scheduled intervals? I'd really like to be able to keep the cron functionality in terms of time/day specification, but farm out the HA of the driver (thing that calls endpoints at the right time) to AWS.
I like how SQS offers web endpoint(s), but from what I can tell you cant schedule them. SWF doesn't seem to be a good fit either.
|
run scheduled task in AWS without cron
|
You can't do what you want in one entry, since the two minute definitions will apply for both hour definitions (as you've identified).
The solution is (unfortunately) use two cron entries. One for 00:00 and one for 13:30.
An alternative is perhaps to execute one script at 00:00. That script would execute your original script, then wait 13.5 hours and then execute that script again. It would be easy to do via a simple sleep command, but I think it's unintuitive, and I'm not sure how cron manages such long running processes (what happens if you edit the crontab - does it kill a spawned job etc.)
|
i want to execute a script twice daily at 00:00 and 13:30 so i write :
0,30 0,13 * * *
it seems wrong for me, because like this, the script will fire at 00:00 , 00:30 , 13:00 and 13:30. Any idea ?
|
execute crontab twice daily at 00h and 13:30
|
To keep my crontab clean, I would just call a shell script and do the fun stuff in the script.
|
How can I store variables in my crontab? I realize it's not shell but say I want to have some constants like a path to my app or something?
|
Variables in crontab?
|
sbin is not in the path when run via cron. Specify the full path to service. This is probably either /sbin/service or /usr/sbin/service. You can find the path on your system by running which service.
|
service service_name start
When i tried running this from cmd line, it works. But when i try to schedule it via cron, i get an error saying
/bin/sh: service: command not found
|
Unable to run a service command via cron
|
It turned out that I could not use the @Scheduled annotation, but I implemented a work-around. In the JavaDoc of the SchedulingConfigurer it is stated that:
[SchedulingConfigurer is] Typically used for setting a specific TaskScheduler bean to be used when executing scheduled tasks or for registering scheduled tasks in a programmatic fashion as opposed to the declarative approach of using the @Scheduled annotation.
Next, I changed the cron job to implement the Runnable interface and then updated my configuration file to implement the SchedulingConfigurer, see below:
@Configuration
@EnableScheduling
@ComponentScan("package.that.contains.the.runnable.job.bean")
public class JobConfiguration implements SchedulingConfigurer {
private static final String cronExpression = "0 0 14 * * *";
private static final String timeZone = "CET";
@Autowired
private Runnable cronJob;
@Bean
CronTrigger cronTrigger() {
return new CronTrigger(cronExpression, TimeZone.getTimeZone(timeZone));
}
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.addCronTask(new CronTask(job, cronTrigger()));
}
}
Please read the JavaDoc of the @EnableScheduling for more information.
Update
As of Spring 4, Spring Jira issue SPR-10456 has been resolved. Consequently, the @Scheduled annotation has a new zone attribute for exactly this purpose, e.g.
@Scheduled(cron = "0 0 14 * * *", zone = "CET")
public void execute() {
// do scheduled job
}
|
How can I configure the time zone for a Spring based @Scheduled cron job?
Background:
I have a job that executes once a day, say 2 PM, using Spring's @Scheduled annotation:
@Scheduled(cron = "0 0 14 * * *")
public void execute() {
// do scheduled job
}
The problem is that 2 PM differs between different servers, because Spring uses on TimeZone.getDefault() internally. Moreover, the JavaDoc of TimeZone.getDefault() states that:
Gets the default TimeZone for this host. The source of the default TimeZone may vary with implementation.
In other words, the time zone is not determined. It may depend on JVM implementation, server time zone configuration, server location, and / or other unknown factors. Consequently, the cron job triggers on different times on different servers, unless there is a way to explicitly set which time zone that should be used?
I am using Spring 3.2.2.
Update
As of Spring 4, Spring Jira issue SPR-10456 has been resolved. Consequently, the @Scheduled annotation has a new zone attribute for exactly this purpose.
|
Provide time zone to Spring @Scheduled?
|
Solution:
*/1 * * * * su -s /bin/sh nobody -c 'cd ~dstrt/www && /usr/local/bin/git pull -q origin master'
|
I was trying to create a cronjob with a task to do a git pull every minute to keep my production site in sync with my master branch.
The git pull needs to be done by the system user nobody, due to the permissions problem. However it seems that the nobody account is not allowed run commands. So I have to create tasks as the root user.
The crontab entry I tried:
*/1 * * * * su -s /bin/sh nobody -c 'cd ~heilee/www && git pull -q origin master' >> ~/git.log
It doesn't work, and I don't know how to debug it.
Could anyone help?
UPDATE1: the git pull command itself is correct. I can run it without errors.
|
Git auto-pull using cronjob
|
Instead of detecting when the script is run from the crontab, it's probably easier to detect when you're running it manually.
There are a lot of environment variables (in the $_ENV array) that are set when you run a script from the command line. What these are will vary depending on your sever setup and how you log in. In my environment, the following environment variables are set when running a script manually that aren't present when running from cron:
TERM
SSH_CLIENT
SSH_TTY
SSH_CONNECTION
There are others too. So for example if you always use SSH to access the box, then the following line would detect if the script is running from cron:
$cron = !isset($_ENV['SSH_CLIENT']);
|
I'm looking for way to PHP to detect if a script was run from a manual invocation on a shell (me logging in and running it), or if it was run from the crontab entry.
I have various maintenance type scripts written in php that i have set to run in my crontab. Occasionally, and I need to run them manually ahead of schedule or if something failed/broken, i need to run them a couple times.
The problem with this is that I also have some external notifications set into the tasks (posting to twitter, sending an email, etc) that I DONT want to happen everytime I run the script manually.
I'm using php5 (if it matters), its a fairly standard linux server environment.
Any ideas?
|
Can PHP detect if its run from a cron job or from the command line?
|
138
Begin the line with 0 0 * * 1,2,3,4,5 <user> <command>. The first fields are minutes and hours. In this case the command will run at midnight. The stars mean: for every day of the month, and for every month. The 1 to 5 specify the days. monday to friday. 6=saturday 0=sunday.
Share
Improve this answer
Follow
answered Feb 4, 2012 at 19:53
MichelMichel
2,56322 gold badges1717 silver badges1414 bronze badges
3
69
1-5 works too..
– Michael Fever
Sep 26, 2016 at 20:09
7
Best way, 0 0 * * 1-5 <script name>
– Balamurugan Thangam
Sep 12, 2017 at 11:28
2
At 9am every day from M-F: ' 0 9 * * 1-5 ' tested on crontab.guru
– Sebastian S
Jan 28, 2018 at 0:13
Add a comment
|
|
Closed. This question is not about programming or software development. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 10 months ago.
Improve this question
Hi I want to create a cron expression excluding saturday and sunday.
|
How to skip saturday and sunday in a cron expression? [closed]
|
Your command is fine!
To run from 7.00 until 19.45, every 15 minutes just use */15 as follows:
*/15 07-19 * * * /path/script
^^^^ ^^^^^
That is, the content */15 in the minutes column will do something every 15 minutes, while the second column, for hours, will do that thing on the specified range of hours.
If you want it to run until 19.00 then you have to write two lines:
*/15 07-18 * * * /path/script
0 19 * * * /path/script
You can have a full description of the command in crontab.guru: https://crontab.guru/#/15_7-19___
|
Is this correct scheduled to run between 07:00 and 19:00 at every 15 minutes?
*/15 07-19 * * * /path/script
|
crontab run every 15 minutes between certain hours
|
Change Minute to be 0. That's it :)
Note: you can check your "crons" in http://cronchecker.net/
Example
|
This question already has answers here:
Running a cron job on Linux every six hours
(7 answers)
Closed 7 years ago.
Is this the correct way for setting a cron job to run every 3 hours?
After setting it this way, cron is executing the command every minute.
|
How to set a cron job to run every 3 hours [duplicate]
|
Try * * * * * to run every minute.
Unfortunately H/1 * * * * does not work due to open defect.
Defect: https://issues.jenkins-ci.org/browse/JENKINS-22129
|
How can I run a job created in Jenkins every one minute ? Am I missing anything?
PS: I'm trying not to use: */1 * * * *
|
Run a Jenkins job every one minute using H/1 * * * *
|
Here is how I run one of my cron containers.
Dockerfile:
FROM alpine:3.3
ADD crontab.txt /crontab.txt
ADD script.sh /script.sh
COPY entry.sh /entry.sh
RUN chmod 755 /script.sh /entry.sh
RUN /usr/bin/crontab /crontab.txt
CMD ["/entry.sh"]
crontab.txt
*/30 * * * * /script.sh >> /var/log/script.log
entry.sh
#!/bin/sh
# start cron
/usr/sbin/crond -f -l 8
script.sh
#!/bin/sh
# code goes here.
echo "This is a script, run by cron!"
Build like so
docker build -t mycron .
Run like so
docker run -d mycron
Add your own scripts and edit the crontab.txt and just build the image and run. Since it is based on alpine, the image is super small.
|
I tried to run a cron job inside a docker container but nothing works for me.
My container has only cron.daily and cron.weekly files.
crontab,cron.d,cron.hourly are absent in my container.
crontab -e is also not working.
My container runs with /bin/bash.
|
How to run a cron job inside a docker container
|
What happens when you type
/home/me/project/myscript.py into the shell?
Can you explicitly use /usr/bin/python in your crontbb command?
Can you either use an absolute path to your test.db or cd to the correct directory then execute your python script?
This is helpful to have debug statements in your python and log some data. Crontab can be very tricky to debug.
|
This question already has answers here:
CronJob not running
(19 answers)
Closed 3 years ago.
My python script is not running under my crontab.
I have placed this in the python script at the top:
#!/usr/bin/python
I have tried doing this:
chmod a+x myscript.py
Added to my crontab -e:
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=""
* * * * * /home/me/project/myscript.py
My /var/log/cron file says:
Sep 21 11:53:02 163-dhcp /USR/SBIN/CROND[2489]: (me) CMD (/home/me/project/myscript.py)
But my script is not running because when I check my sql database, nothing has changed. If I run it directly in the terminal like so:
python /home/me/project/myscript.py
I get the correct result.
This is the myscript.py:
#!/usr/bin/python
import sqlite3
def main():
con = sqlite3.connect("test.db")
with con:
cur = con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS testtable(Id INTEGER PRIMARY KEY, Name TEXT)")
cur.execute("INSERT INTO testtable(Name) VALUES ('BoB')")
cur.execute("SELECT * FROM testtable")
print cur.fetchall()
if __name__ == "__main__":
main()
Per comments: Yes, /usr/bin/python exists. I can also run the python script directly using just /home/me/project/myscript.py. chmod a+x myscript.py
0 works. So I don't believe this is the cause?
|
Crontab not executing a Python script? [duplicate]
|
You might be triggering the Linux out-of-memory (OOM) killer. Check dmesg for messages about it. It says which process was killed when this happens.
|
I am working on a CRON job that invokes a PHP script which does a lot of database work with loops.
It executes properly when I limit the data set, but when I run it against the full data set, the script errors out with a message:
Killed
set_time_limit is (0) and memory_limit is (-1)
Here is the code section where it consistently dies:
echo "I'm in _getMemberDemographicAttrs\n";
if (! empty ( $member_id )) {
$query .= ' AND member_id = ' . $member_id;
}
$result = mysql_query ( $query, $this->_db );
if ($result) {
while ( $rule = mysql_fetch_assoc ( $result ) ) {
$rules [] = $rule;
}
if (! empty ( $rules )) {
mysql_free_result ( $result );
echo "I'm leaving _getMemberDemographicAttrs\n";
return $rules;
}
}
The output looks like this:
I'm in _getMemberDemographicAttrs<br/>
I'm leaving _getMemberDemographicAttrs<br/>
I'm in _getMemberDemographicAttrs<br/>
I'm leaving _getMemberDemographicAttrs<br/>
I'm in _getMemberDemographicAttrs<br/>
Killed
I've never seen this generic Killed error message and I'm wondering what is causing it to be killed?
|
Generic "Killed" error in PHP script
|
cron is the general name for the service that runs scheduled actions. crond is the name of the daemon that runs in the background and reads crontab files. A crontab is a file containing jobs in the format
minute hour day-of-month month day-of-week command
crontabs are normally stored by the system in /var/spool/<username>/crontab. These files are not meant to be edited directly. You can use the crontab command to invoke a text editor (what you have defined for the EDITOR env variable) to modify a crontab file.
There are various implementations of cron. Commonly there will be per-user crontab files (accessed with the command crontab -e) as well as system crontabs in /etc/cron.daily, /etc/cron.hourly, etc.
In your first example you are scheduling a job via a crontab. In your second example you're using the at command to queue a job for later execution.
|
I am not able to understand the answer for this question: "What's the difference between cron and crontab." Are they both schedulers with one executing the files once and the other executing the files on a regular interval OR does cron schedule a job and crontab stores them in a table or file for execution?
Wiki page for Cron mentions :
Cron is driven by a crontab (cron table) file, a configuration file
that specifies shell commands to run periodically on a given schedule.
But wiki.dreamhost for crontab mentiones :
The crontab command, found in Unix and Unix-like operating systems, is
used to schedule commands to be executed periodically. It reads a
series of commands from standard input and collects them into a file
known as a "crontab" which is later read and whose instructions are
carried out.
Specifically, When I schedule a job to be repeated : (Quoting from wiki)
1 0 * * * printf > /var/log/apache/error_log
or executing a job only once
at -f myScripts/call_show_fn.sh 1:55 2014-10-14
Am I doing a cron function in both the commands which is pushed in crontab OR is the first one a crontab0 and the second a crontab1 function?
|
Difference between Cron and Crontab?
|
Try creating a shell script like the one below:
#!/bin/bash
mysql --user=[username] --password=[password] --database=[db name] --execute="DELETE FROM tbl_message WHERE DATEDIFF( NOW( ) , timestamp ) >=7"
You can then add this to the cron
|
I would like to purge my SQL database from all entires older than 1 week, and I'd like to do it nightly. So, I'm going to set up a cron job. How do I query mySQL without having to enter my password manually every time?
The query in PHP is as follows:
mysql_query("DELETE FROM tbl_message WHERE DATEDIFF( NOW( ) , timestamp ) >=7");
Is there a way to run this as a shell script? If not, is there a way of making cron run a php file?
|
Run a mySQL query as a cron job?
|
Use crontab -l > file to list current user's crontab to the file, and crontab file, to install new crontab.
|
I'm trying to add a line to the crontab on Ubuntu.
Right now, I'm doing crontab -e and editing the crontab there.
However, I can't seem to find the real crontab file, since crontab -e seems to give you a temporary working copy.
/etc/crontab looks like the system crontab.
What is the path of the crontab that crontab -e saves to?
Thanks!
|
Appending to crontab with a shell script on Ubuntu
|
A crontab file has five fields for specifying day , date and time followed by the command to be run at that interval.
* * * * * command to be executed
- - - - -
| | | | |
| | | | +----- day of week (0 - 6) (Sunday=0)
| | | +------- month (1 - 12)
| | +--------- day of month (1 - 31)
| +----------- hour (0 - 23)
+------------- min (0 - 59)
* in the value field above means all legal values as in braces for that column.
You could use 0 1,13 * * * which means for every 1AM and 1PM.
0 1,13 * * * rm /var/www/*/somedir/index.php > /home/someuser/cronlogs/some.log 2>&1
where * can be replaced by different domain names.
|
I need unix cron command to run every 12 hours.
I have 500+ sub blogs in my server.
This is the file i want to run every 12 hours
http://*.mysite.com/somedir/index.php
Where * is my subdomain of my blogs.
I need cron command for all blogs.
Is it possible to run all of them with single command?
OR do i have to create command for each blog?
|
cron command to run every 12 hours
|
There is no direct cron expression for every 2 weeks. I use the following cron expression, which is similar to 2 weeks, but not exactly for 2 weeks.
cron expression for every 2 weeks on the 1st and the 15th of every month at 1:30 AM:
30 1 1,15 * *
|
Here is a cron expression that I tried: 0 0 0 */14 * ?. It creates the following schedule:
Start Time:
Friday, September 8, 2017 1:25 AM
Next Times:
Friday, September 15, 2017, 12:00 AM
Friday, September 29, 2017, 12:00 AM
Sunday, October 1, 2017, 12:00 AM
Sunday, October 15, 2017, 12:00 AM
Sunday, October 29, 2017, 12:00 AM
This expression is working for every 2 weeks in every month, but my requirement is it has to run for every 2 weeks. I mean after executing September 29th, the next date should be October 13, but it schedules for October 1.
|
how to create a cron expression for every 2 weeks
|
I finally got it to work with this cron expression 0 0 0 * * * but I had to set the time zone in the scheduler class like this.
@Scheduled(cron = "0 0 0 * * *",zone = "Indian/Maldives")
|
I am trying to schedule a task in Spring which is to be run everyday at midnight. I followed the official guide from Spring and made the scheduler class as below:
@Component
public class OverduePaymentScheduler {
@Scheduled(cron = "0 0 0 * * *")
public void trackOverduePayments() {
System.out.println("Scheduled task running");
}
}
However the task does not run when the clock hits 12am. I got the cron expression from the documentation for quartz scheduler at this link.
The scheduler is executed fine if I change the cron expression to "*/10 * * * * *" which runs every ten seconds.
So what am I doing wrong?
|
Spring Scheduling - Cron expression for everyday at midnight not working?
|
You can see the date, time, user and command of previously executed cron jobs using:
grep CRON /var/log/syslog
This will show all cron jobs. If you only wanted to see jobs run by a certain user, you would use something like this:
grep CRON.*\(root\) /var/log/syslog
Note that cron logs at the start of a job so you may want to have lengthy jobs keep their own completion logs; if the system went down halfway through a job, it would still be in the log!
Edit: If you don't have root access, you will have to keep your own job logs. This can be done simply by tacking the following onto the end of your job command:
&& date > /home/user/last_completed
The file /home/user/last_completed would always contain the last date and time the job completed. You would use >> instead of > if you wanted to append completion dates to the file.
You could also achieve the same by putting your command in a small bash or sh script and have cron execute that file.
#!/bin/bash
[command]
date > /home/user/last_completed
The crontab for this would be:
* * * * * bash /path/to/script.bash
|
I want to get the details of the last run cron job. If the job is interrupted due to some internal problems, I want to re-run the cron job.
Note: I don't have superuser privilege.
|
Details of last ran cron job in Unix-like systems?
|
The answer would be dependent on the variant/extension of cron you are using. Some variants do not handle the Daylight Saving Time, leading to missing jobs and twice run of the job.
If you are using the Paul Vixie cron, then it does handle the DST changes. As per the cron man page:
cron checks each minute to see if its spool directory's
modtime (or the modtime on /etc/crontab) has changed
And further, with reference to Daylight Saving Time (The 2nd paragraph clearly explains your answer)
Daylight Saving Time and other time changes
Local time changes of less than three hours, such as those caused by
the start or end of Daylight Saving Time, are handled specially. This
only applies to jobs that run at a specific time and jobs that are run
with a granularity greater than one hour. Jobs that run more fre-
quently are scheduled normally.
If time has moved forward, those jobs that would have run in the inter-
val that has been skipped will be run immediately. Conversely, if time
has moved backward, care is taken to avoid running jobs twice.
Time changes of more than 3 hours are considered to be corrections to
the clock or timezone, and the new time is used immediately.
So, whenever the time shifts may be 2:59:59 or at 3:00:00, cron's taking care of the job runs by handling the situation and running only the missed ones and avoids running the already ran jobs.
|
If Cron has a job scheduled to run at 2 am and one at 3 am how would those jobs be affected by daylight savings time?
When the time shifts back an hour does the time go from 2:59:59 am to 2:00:00 am directly? Meaning that the 2 am job would run twice and the 3 am job would run once? Or is does the time first change to 3:00:00 am and then 2:00:00 am causing both jobs to run twice?
When the time shifts forward an hour does the time go from 1:59:59 am to 3:00:00 am causing the 2 am job to not run and the 3 am job to run once? Or does the time shift from 2:00:00 to 3:00:00 am causing both jobs to run once?
In short what I am wondering is when gaining an hour does the 3 am hour happen once or twice and and losing an hour does the 2 am hour happen at all. I have not been able to find anything about this when looking on Google.
|
Daylight Savings and Cron
|
* * * * * echo "hello" > /tmp/helloFile_$(date +\%Y\%m\%d\%H\%M\%S).txt
You just need to escape the percent signs.
Other date formats:
http://www.cyberciti.biz/faq/linux-unix-formatting-dates-for-display/
|
I've created a Cron task at my webhost to daily backup my database and I would like it to append the current date to the filename.
My Cron job looks like this
mysqldump -u username -pPassword db_name > www/db_backup/db_backup+date%d%m%y.sql
But the file I get is this: db_backup+date no file extension or date.
I've also tried this command
mysqldump -u username -pPassword db_name > www/db_backup/db_backup_'date +%d%m%y'.sql
but that doesn't even give an file output.
What is the right syntax for getting the date appended to my file??
|
Append current date to the filename via Cron?
|
This question has also been asked on serverfault and has garnered a couple additional answers
The following is a paraphrased version of Marco's solution:
(Not sure if best etiquette is not providing a link only answer or not copying someone else's solution)
Create a environment file with a temporary cron entry
* * * * * /usr/bin/env > /home/username/cron-env
Then create a shell script called run-as-cron which executes the command using that environment.
#!/bin/sh
. "$1"
exec /usr/bin/env -i "$SHELL" -c ". $1; $2"
Give it execute permission
chmod +x run-as-cron
and then it is then used like this:
./run-as-cron <cron-environment> <command>
e.g.
./run-as-cron /home/username/cron-env 'echo $PATH'
|
I added a cron job recently, but made a mistake in the path while giving the command and hence, the job never succeeded. Is there some way to test the cron changes we have done?
Please note that I had indeed copied and pasted the command from my command line and it was just an stray keypress that caused this.
|
Test run cron entry
|
I played around with this all afternoon and couldn't find a better solution. Here is what I have come up with
bundle install --binstubs
and then run
bin/rake daily:stats
|
I am trying to use whenever to execute a rake task onces a day. Im getting this error
/bin/bash: bundle: command not found
/home/app/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems/dependency.rb:247:in `to_specs': Could not find bundler (>= 0) amongst [minitest-1.6.0, rake-0.8.7, rdoc-2.5.8] (Gem::LoadError)
from /home/app/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems/dependency.rb:256:in `to_spec'
from /home/app/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems.rb:1210:in `gem'
from /home/app/.rvm/gems/ruby-1.9.2-p180/bin/bundle:18:in `<main>'
Here is my crontab
# Begin Whenever generated tasks for: /home/af/www/app/releases/20120216172204/config/schedule.rb
PATH=/home/af/.rvm/gems/ruby-1.9.2-p180@global/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
0 0 * * * /bin/bash -l -c 'cd /home/af/www/app/releases/20120216172204 && rvm 1.9.1-p180; RAILS_ENV=production /home/af/.rvm/gems/ruby-1.9.2-p180/bin/bundle exec rake daily:stats --silent >> /home/af/www/app/releases/20120216172204/log/cron.log 2>&1'
# End Whenever generated tasks for: /home/af/www/app/releases/20120216172204/config/schedule.rb
I'm at a loss as to why it isn't working. If I run the command:
cd /home/af/www/app/releases/20120216172204 && rvm 1.9.1-p180; RAILS_ENV=production /home/af/.rvm/gems/ruby-1.9.2-p180/bin/bundle exec rake daily:stats --silent >> /home/af/www/app/releases/20120216172204/log/cron.log 2>&1
It works fine, not sure whats going on here.
|
Rails cron whenever, bundle: command not found
|
It depends on how strictly you have to adhere to that minute interval and if your node script is doing anything else in the meantime. If the only thing the script does is run something every X, I would strongly consider just having your node script do X instead, and scheduling it using the appropriate operating system scheduler.
If you build and run this in node, you have to manage the lifecycle of the app and make sure it's running, recover from crashes, etc. Just executing once a minute via CRON is much more straightforward and in my opinion conforms more to the Unix Philosophy.
|
I'm learning node.js and just set up an empty Linux Virtual Machine and installed node.
I'm running a function constantly every minute
var request = require('request')
var minutes = 1, the_interval = minutes * 60 * 1000
setInterval(function() {
// Run code
})
}, the_interval);
And considering adding some other functions based on current time. - (e.g. run function if dateTime = Sunday at noon)
My question is are there any disadvantages to running a set up like this compared to a traditional cron job set up?
Keep in mind I have to run this function in node every minute anyways.
|
Set Interval in Node.js vs. Cron Job?
|
Your syntax is slightly wrong. Say:
*/15 * * * * command
|
|--> `*/15` would imply every 15 minutes.
* indicates that the cron expression matches for all values of the field.
/ describes increments of ranges.
|
How can I run a cron job every 15 mins on Jenkins?
This is what I've tried :
On Jenkins I have a job set to run every 15 mins using this cron syntax :
14 * * * *
But the job executes every hour instead of 15 mins.
I'm receiving a warning about the format of the cron syntax :
Spread load evenly by using ‘H * * * *’ rather than ‘14 * * * *’
Could this be the reason why the cron job executes every hour instead of 15 mins ?
|
Configure cron job to run every 15 minutes on Jenkins
|
I found the answer:
$ crontab -l
# m h dom mon dow command
* * * * * export DISPLAY=:0.0 && export XAUTHORITY=/home/ravi/.Xauthority && sudo -u ravi /usr/bin/notify-send Hey "How are you"
|
I need to show a notification from a cron job. My crontab is something like:
$ crontab -l
# m h dom mon dow command
* * * * * Display=:0.0 /usr/bin/notify-send Hey "How are you"
I checked /var/log/syslog and the command is actually executed every minute but it doesn't pop up the notification.
Can anybody help me understand why?
|
Cron with notify-send
|
The working directory of the script may be different when run from a cron. Additionaly, there was some confusion about PHPs require() and include(), which caused confusion about the working directory really being the problem:
include('foo.php') // searches for foo.php in the same directory as the current script
include('./foo.php') // searches for foo.php in the current working directory
include('foo/bar.php') // searches for foo/bar.php, relative to the directory of the current script
include('../bar.php') // searches for bar.php, in the parent directory of the current working directory
|
If a PHP script is run as a cron script, the includes often fail if relative paths are used. For example, if you have
require_once('foo.php');
the file foo.php will be found when run on the command line, but not when run from a cron script.
A typical workaround for this is to first chdir to the working directory, or use absolute paths. I would like to know, however, what is different between cron and shell that causes this behavior. Why does it fail when using relative paths in a cron script?
|
Relative path not working in cron PHP script
|
You could tell wget to not download the contents in a couple of different ways:
wget --spider http://www.example.com/cronit.php
which will just perform a HEAD request but probably do what you want
wget -O /dev/null http://www.example.com/cronit.php
which will save the output to /dev/null (a black hole)
You might want to look at wget's -q switch too which prevents it from creating output
I think that the best option would probably be:
wget -q --spider http://www.example.com/cronit.php
that's unless you have some special logic checking the HTTP method used to request the page
|
I tried to do a cron and run a url every 5 mintues.
I tried to use WGET however I dont want to download the files on the server, all I want is just to run it.
This is what I used (crontab):
*/5 * * * * wget http://www.example.com/cronit.php
Is there any other command to use other than wget to just run the url and not downlaod it?
|
Using WGET to run a cronjob PHP
|
If the first command is required to be completed first, you should separate them with the && operator as you would in the shell. If the first fails, the second will not run.
|
I have two commands in a cron job like this:
mysql -xxxxxx -pyyyyyyyyyyv -hlocalhost -e "call MyFunction1";wget -N http://mywebsite.net/path/AfterMyFunction1.php
but it seems to me that both of them are running at the same time.
How can I make the first command run and when it completes, execute the second command?
Also the AfterMyFunction1.php have javascript http requests that are not executed when I use wget. It works if I opened AfterMyFunction1.php in my webbrowser.
|
Running two commands sequentially in a cron job?
|
60
Assuming you are using a unix OS, you would do the following.
edit the crontab file using the command
crontab -e
add a line that resembles the one below
*/2 * * * * /Desktop/downloads/file_example.py
this can be used to run other scripts simply use the path to the script needed i.e.
*/2 * * * * /path/to/script/to/run.sh
An explanation of the timing is below (add a star and slash before number to run every n timesteps, in this case every 2 minutes)
* * * * * command to be executed
- - - - -
| | | | |
| | | | ----- Day of week (0 - 7) (Sunday=0 or 7)
| | | ------- Month (1 - 12)
| | --------- Day of month (1 - 31)
| ----------- Hour (0 - 23)
------------- Minute (0 - 59)
Share
Improve this answer
Follow
edited Jan 24, 2016 at 17:35
CommunityBot
111 silver badge
answered Aug 2, 2012 at 9:57
olly_ukolly_uk
11.7k33 gold badges3939 silver badges4545 bronze badges
9
The above code is useful , actually some times i have found that creating bash scripts(with .sh extension) and running those, can i know about this concept and both differs or same
– Shiva Krishna Bavandla
Aug 2, 2012 at 10:02
you can run them exactly teh same way as long as the shebang line, e.g.#!/usr/bin/sh is included in the file
– olly_uk
Aug 2, 2012 at 10:04
1
look here en.wikipedia.org/wiki/Shebang_%28Unix%29 for explanation of shebang lines
– olly_uk
Aug 2, 2012 at 10:09
1
Thank you very much generally we will run the file using "python" command but here in the above example directly the path is given without command whether it automatically takes that command?
– Shiva Krishna Bavandla
Aug 2, 2012 at 10:11
1
don't you need to write python just before the python script to execute it?
– Samadi Salahedine
Jul 13, 2018 at 8:57
|
Show 4 more comments
|
Hi I have created a python file for example as file_example.py
The file will output the sensex value
Suppose the path of the file on linux system is /Desktop/downloads/file_example.py
and I normally will run the file like python file_example.py
But I want to set a cron job to run the python file every 2 min which is located at the above path
Can anyone please let me know how to do this
Edited Code:
I had edited the code and created a bash script with the name test.sh as indicated below
#!/bin/bash
cd /Desktop/downloads/file_example.py
python file_example.py 2>log.txt
When I run the above file, the following error is displayed:
sh-4.2$ python test.sh
File "test.sh", line 3
python test.py 2>log.txt
^
SyntaxError: invalid syntax
|
How to run a python file using cron jobs
|
No, you can't do that. From the man page:
There is no way to split a single command line onto multiple lines,
like the shell's trailing "\".
You can put the commands in a script and run it.
|
I have two python scripts:
#1. getUrl.py # used to collect target urls which takes about 10 mins and used as the input for the next script
#2. monitoring.py # used to monitoring the website.
00 01 * * * /usr/bin/python /ephemeral/monitoring/getUrl.py > /ephemeral/monitoring/input && /usr/bin/python /ephemeral/monitoring/monitoring.py >> /ephemeral/monitoring/output
I put the this command in crontab and wondering how could I write that long command into two or three lines. Something like the python line separator example below but for Crontab command, so it is more readable:
>>> print \
... 'hel\
... llo'
helllo
|
Crontab Command Separate Line
|
R CMD BATCH is all we had years ago. It makes i/o very hard and leaves files behind.
Things got better, first with littler and then too with Rscript. Both can be used for 'shebang' lines such as
#!/usr/bin/r
#!/usr/bin/Rscript
and both can be used with packages like getopt and optparse --- allowing you to write proper R scripts that can act as commands. If have dozens of them, starting with simple ones like this which I can call as install.r pkga pkgb pkgc and which will install all three and their dependencies) for me from the command-line without hogging the R prompt:
#!/usr/bin/env r
#
# a simple example to install one or more packages
if (is.null(argv) | length(argv)<1) {
cat("Usage: installr.r pkg1 [pkg2 pkg3 ...]\n")
q()
}
## adjust as necessary, see help('download.packages')
repos <- "http://cran.rstudio.com"
## this makes sense on Debian where no packages touch /usr/local
lib.loc <- "/usr/local/lib/R/site-library"
install.packages(argv, lib.loc, repos)
And just like Karl, I have cronjobs calling similar R scripts.
Edit on 2015-11-04: As of last week, littler is now also on CRAN.
|
I am automating some webscraping with R in cron and sometimes I use R CMD BATCH and sometimes I use Rscript.
To decide which one to use I mainly focus if I want the .Rout file or not.
But reading the answers to some questions here in SO (like this or this) it seems that Rscript is preferred to R CMD BATCH.
So my questions are:
Besides the fact that the syntax is a little different and R CMD BATCH saves an .Rout file while Rscript does not, what are the main differences between the two of them?
When should I prefer one over another? More specifically, in the cron0 job above mentioned, is one of them preferred?
I have not used yet cron1, how is it different from both cron2 and cron3?
|
Why (or when) is Rscript (or littler) better than R CMD BATCH?
|
I'd say "sort of". The things to remember about task queues are:
1) a limit of operations per minute/hour/day is not the same as repeating something at regular intervals. Even with the token bucket size set to 1, I don't think you're guaranteed that those repetitions will be evenly spaced. It depends how serious they are when they say the queue is implemented as a token bucket, and whether that statement is supposed to be a guaranteed part of the interface. This being labs, nothing is guaranteed yet.
2) if a task fails then it's requeued. If a cron job fails, then it's logged and not retried until it's due again. So a cron job doesn't behave the same way either as a task which adds a copy of itself and then refreshes your feed, or as a task which refreshes your feed and then adds a copy of itself.
It may well be possible to mock up cron jobs using tasks, but I doubt it's worth it. If you're trying to work around a cron job which takes more than 30 seconds to run (or hits any other request limit), then you can split the work up into pieces, and have a cron job which adds all the pieces to a task queue. There was some talk (in the GAE blog?) about asynchronous urlfetch, which might be the ultimate best way of updating RSS feeds.
|
The latest Google App Engine release supports a new Task Queue API in Python. I was comparing the capabilities of this API vs the already existing Cron service. For background jobs that are not user-initiated, such as grabbing an RSS feed and parsing it on a daily interval. Can and should the Task Queue API be used for non-user initiated requests such as this?
|
Google App Engine - Task Queues vs Cron Jobs
|
I recently (April 2018) installed and ran certbot (version 0.22.2) on an Ubuntu 16.04 server, and a renewal cron job was created automatically in /etc/cron.d/certbot.
Here's the cron job that was created:
# /etc/cron.d/certbot: crontab entries for the certbot package
#
# Upstream recommends attempting renewal twice a day
#
# Eventually, this will be an opportunity to validate certificates
# haven't been revoked, etc. Renewal will only occur if expiration
# is within 30 days.
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
0 */12 * * * root test -x /usr/bin/certbot -a \! -d /run/systemd/system && perl -e 'sleep int(rand(3600))' && certbot -q renew
Please check this before putting a new Cron job.
Update (From @Hamish Downer's comment):
It's worth being aware that the above cron job won't run certbot renew if /run/systemd/system is present - this is because instead a systemd timer is running certbot - read more about certbot and systemd timers here.
|
I've seen conflicting recommendations. From the eff.org docs:
if you're setting up a cron or systemd job, we recommend running it twice per day... Please select a random minute within the hour for your renewal tasks.
I've also seen recommendations for weekly jobs.
I'm not a cron expert, so I'd prefer an answer with detailed steps for setting up the cron job.
|
How do I schedule the Let's Encrypt certbot to automatically renew my certificate in cron?
|
I have used below cron
php /full-path-to-cron-file/cron.php /test/index
source: http://www.asim.pk/2009/05/14/creating-and-installing-crontabs-using-codeigniter/
This works for me.
Thanks to all
|
I am using CodeIgniter for my website. I have to use cron job to run one of controller function. I am using route in website. And also I am not using index.php in URL.
e.g. http://example.com/welcome/show, here welcome is my controller and show is function name of that controller.
I have used like this,
0 * * * * php /home/username/public_html/welcome/show
It is giving 'No such directory'
How can I set cron jon in cPanel for above URL.
|
How to set cron job URL for CodeIgniter?
|
Short answer: use the scheduler add-on: http://addons.heroku.com/scheduler
Long answer: When you do heroku run, we
spin up a dyno
put your code on it
execute your command, wait for it to finish
throw the dyno away
Any changes you made to crontab would be immediately thrown away. Everything is ephemeral, you cannot edit files on heroku, just push new code.
|
I created an app that uses the whenever gem. The gem creates cron jobs. I got it working locally but can't seem to get it working on heroku cedar. What's the command to do this?
running:
heroku run whenever --update-crontab job1
doesn't work
|
"Whenever" gem running cron jobs on Heroku
|
35
That's what cronjobs are made for. man crontab assuming you are running a linux server. If you don't have shell access or no way to setup cronjobs, there are free services that setup cronjobs on external servers and ping one of your URLs.
Share
Improve this answer
Follow
answered Sep 23, 2008 at 10:28
Armin RonacherArmin Ronacher
32.2k1313 gold badges6666 silver badges6969 bronze badges
2
1
Do you know about anyone you could recommend?
– ehm
Sep 23, 2008 at 10:38
3
siteuptime.com can be set to ping pages on your site at regular intervals - ostensibly checking for uptime, but could trigger your jobs if they're in an accessible script. Best way is to set up your own crontab/scheduled task though, so unexpected user accesses can't re-run your jobs
– ConroyP
Sep 23, 2008 at 10:42
Add a comment
|
|
I have a site on my webhotel I would like to run some scheduled tasks on. What methods of achieving this would you recommend?
What I’ve thought out so far is having a script included in the top of every page and then let this script check whether it’s time to run this job or not.
This is just a quick example of what I was thinking about:
if ($alreadyDone == 0 && time() > $timeToRunMaintainance) {
runTask();
$timeToRunMaintainance = time() + $interval;
}
Anything else I should take into consideration or is there a better method than this?
|
PHP: running scheduled jobs (cron jobs)
|
0 18 * * * command to be executed
^ you need to set the minute, too. Else it would be running every minute on the 18th hour
How to setup a cronjob in general:
# * * * * * command to execute
# │ │ │ │ │
# │ │ │ │ │
# │ │ │ │ └───── day of week (0 - 6) (0 to 6 are Sunday to Saturday, or use names; 7 is Sunday, the same as 0)
# │ │ │ └────────── month (1 - 12)
# │ │ └─────────────── day of month (1 - 31)
# │ └──────────────────── hour (0 - 23)
# └───────────────────────── min (0 - 59)
What does Asterisk (*) mean
The asterisk indicates that the cron expression matches for all values of the field. E.g., using an asterisk in the 4th field (month) indicates every month.
Sidenote
Other special characters in cronjobs
Slash ( / )
Slashes describe increments of ranges. For example 3-59/15 in the 1st field (minutes) indicate the third minute of the hour and every 15 minutes thereafter. The form "*/..." is equivalent to the form "first-last/...", that is, an increment over the largest possible range of the field.
Comma ( , )
Commas are used to separate items of a list. For example, using "MON,WED,FRI" in the 5th field (day of week) means Mondays, Wednesdays and Fridays.
Hyphen ( - )
Hyphens define ranges. For example, 2000-2010 indicates every year between 2000 and 2010 AD, inclusive.
Percent ( % )
Percent-signs (%) in the command, unless escaped with backslash (), are changed into newline characters, and all data after the first % are sent to the command as standard input.
(source: https://en.wikipedia.org/wiki/Cron)
|
I'm trying to figure out how to set cron to run every day at 6 p.m. Is this correct?
The reason I'm asking is this is for a production server, so I need to be sure.
* 18 * * *
|
Cron every day at 6 pm
|
Try
0 16 ? * 1 *
The question marks "says" that it must no be executed everyday, so it must check the week day value.
|
In Amazon AWS CloudWatch it is possible to run a rule according to a schedule that is defined in a cron expression.
The rules for this are outlined here.
After some trying around, I wasn't able to compose an expression that will run once a week (e.g. at 4 pm on Sunday). The following attempts were rejected by CloudWatch with the message Parameter ScheduleExpression is not valid...
0 16 * * SUN *
0 16 * * 6 *
0 16 * * SUN-SUN *
0 16 * * 6-6 *
|
cron expression in AWS CloudWatch: How to run once a week
|
1-56/5 * * * * /my/script
This should work on vixiecron, I'm not sure about other implementations.
|
I know that I can have something run every five minutes in cron with a line like:
*/5 * * * * /my/script
What if I don't want it running at 12:00, 12:05, 12:10, but rather at 12:01, 12:06, 12:11, etc? I guess I can do this:
1,6,11,16,21,26,31,36,41,46,51,56 * * * * /my/script
...but that's ugly. Is there a more elegant way to do it?
|
How do I make cron run something every "N"th minute, where n % 5 == 1?
|
You cannot, you can use either multiple values OR a range
0 1,2,3,4,5,6,7,8,10,11,12,13,14,15 * * *
Source:
Time tags are separated by spaces. Do not use spaces within a tag,
this will confuse cron. All five tags must be present. They are a
logical AND of each other. There is another space between the last
time tag and the first command.
A time tag can be a wildcard "*", which means "all". It can be one
value, several values, a range, or a fractional range.
|
I need a cron statement to run for few hours eg 1-8 then 10-15.
In this case will the following statement work,
0 1-8,10-15 * * *
If not can anyone help me?
Thanks in advance,
Gnik
|
How to create cron statement to run for multiple hours
|
The $_GET[] & $_POST[] associative arrays are only initialized when your script is invoked via a web server. When invoked via the command line, parameters are passed in the $argv array, just like C.
Contains an array of all the arguments passed to the script when
running from the command line.
Your command would be:
* 3 * * * /path_to_script/cronjob.php username=test password=test code=1234
You would then use parse_str() to set and access the paramaters:
<?php
var_dump($argv);
/*
array(4) {
[0]=>
string(27) "/path_to_script/cronjob.php"
[1]=>
string(13) "username=test"
[2]=>
string(13) "password=test"
[3]=>
string(9) "code=1234"
}
*/
parse_str($argv[3], $params);
echo $params['code']; // 1234
|
I am new at cron jobs and am not sure whether this would would work.
For security purposes I thought about making a one page script that looks for certain GET values (a username, a password, and a security code) to make sure that only the computer and someone that knows all 3 can run the command.
I made the script and it works running it in a browser but is it possible to run the cron job with GET values?
a example would be me running
* 3 * * * /path_to_script/cronjob.php?username=test&password=test&code=1234
Is this possible?
|
Passing $_GET parameters to cron job
|
Automated Tasks: Cron
Cron is a time-based scheduling service in Linux / Unix-like computer operating systems. Cron job are used to schedule commands to be executed periodically.
You can setup commands or scripts, which will repeatedly run at a set time. Cron is one of the most useful tool in Linux or UNIX like operating systems. The cron service (daemon) runs in the background and constantly checks the /etc/crontab file, /etc/cron./* directories. It also checks the /var/spool/cron/ directory.
Configuring Cron Tasks
In the following example, the crontab command shown below will activate the cron tasks automatically every ten minutes:
*/10 * * * * /usr/bin/php /opt/test.php
In the above sample, the */10 * * * * represents when the task should happen. The first figure represents minutes – in this case, on every "ten" minute. The other figures represent, respectively, hour, day, month and day of the week.
* is a wildcard, meaning "every time".
Start with finding out your PHP binary by typing in command line:
whereis php
The output should be something like:
php: /usr/bin/php /etc/php.ini /etc/php.d /usr/lib64/php /usr/include/php /usr/share/php /usr/share/man/man1/php.1.gz
Specify correctly the full path in your command.
Type the following command to enter cronjob:
crontab -e
To see what you got in crontab.
EDIT 1:
To exit from vim editor without saving just click:
Shift+:
And then type q!
|
In our centos6 server. I would like to execute a php script in cron job as apache user but unfortunately it does not work.
Here is the edition of crontab (crontab -uapache -e)
24 17 * * * php /opt/test.php
and here is the source code of "test.php" file which works fine with "apache" user as owner.
<?php exec( 'touch /opt/test/test.txt');?>
I try to replace php with full path of php (/usr/local/php/bin/php) but also it doesn't work.
|
Execute PHP script in cron job
|
Don't call sh but bash. source is a bash command.
- sh scripts/my_script.bash
+ bash scripts/my_script.bash
Or just
chmod +x scripts/my_script.bash
./scripts/my_script.bash
since you added the bash shebang.
|
I want to have a cron job execute a python script using an already existing anaconda python environment called my_env. The only thing I can think to do is have the cron job run a script called my_script.bash which in turn activates the env and then runs the python script.
#!/bin/bash
source activate my_env
python ~/my_project/main.py
Trying to execute this script from the command lines doesn't work:
$ sh scripts/my_script.bash
scripts/my_script.bash: 9: scripts/my_script.bash: source: not found
What do I need to do to make sure the proper environment is activated. Its ok to explain it to me like I'm 5.
|
run a crontab job using an anaconda env
|
After hours and hours work, I created a solution like the below. I copy paste for other people that can benefit.
First create a script file and give this file executable permission.
# cd /etc/cron.daily/
# touch /etc/cron.daily/dbbackup-daily.sh
# chmod 755 /etc/cron.daily/dbbackup-daily.sh
# vi /etc/cron.daily/dbbackup-daily.sh
Then copy following lines into file with Shift+Ins
#!/bin/sh
now="$(date +'%d_%m_%Y_%H_%M_%S')"
filename="db_backup_$now".gz
backupfolder="/var/www/vhosts/example.com/httpdocs/backups"
fullpathbackupfile="$backupfolder/$filename"
logfile="$backupfolder/"backup_log_"$(date +'%Y_%m')".txt
echo "mysqldump started at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
mysqldump --user=mydbuser --password=mypass --default-character-set=utf8 mydatabase | gzip > "$fullpathbackupfile"
echo "mysqldump finished at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
chown myuser "$fullpathbackupfile"
chown myuser "$logfile"
echo "file permission changed" >> "$logfile"
find "$backupfolder" -name db_backup_* -mtime +8 -exec rm {} \;
echo "old files deleted" >> "$logfile"
echo "operation finished at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
echo "*****************" >> "$logfile"
exit 0
Edit:
If you use InnoDB and backup takes too much time, you can add "single-transaction" argument to prevent locking. So mysqldump line will be like this:
mysqldump --user=mydbuser --password=mypass --default-character-set=utf8
--single-transaction mydatabase | gzip > "$fullpathbackupfile"
|
I tried many scripts for database backup but I couldn't make it. I want to backup my database every hour.
I added files to "/etc/cron.hourly/" folder, changed its chmod to 755, but it didn't run.
At least I write my pseudo code.
I would be happy if you can write a script for this operation and tell me what should I do more ?
After adding this script file to /etc/cron.hourly/ folder.
Get current date and create a variable, date=date(d_m_y_H_M_S)
Create a variable for the file name, filename="$date".gz
Get the dump of my database like this mysqldump --user=my_user --password=my_pass --default-character-set=utf8 my_database | gzip > "/var/www/vhosts/system/example.com/httpdocs/backups/$("filename")
Delete all files in the folder /var/www/vhosts/system/example.com/httpdocs/backups/ that are older than 8 days
To the file "/var/www/vhosts/system/example.com/httpdocs/backup_log.txt", this text will be written: Backup is created at $("date")
Change the file owners (chown) from root to "my_user". Because I want to open the backup and log files from the "my_user" FTP account.
I don't want an email after each cron. >/dev/null 2>&1 will be added.
|
Linux shell script for database backup
|
First: check where on your system the executable aws is stored. Use this command:
$ which aws
/usr/bin/aws # example output, can differ in your system
Now, place a variable called $PATH in your crontab before the script:
PATH=/usr/bin:/usr/local/bin
Those paths separated by : define where should be search for the exectable. In the example above it's /usr/bin. You have to check all executables in your cron job that they are available.
Another thing: try to avoid path with a tilde (~) in cronjobs. Use /home/user instead.
|
So I have a script to download a file from AWS daily and append it to a spread sheet. To do this I have set up a cronjob.
The Script works fine when I run it manually, but does not work when running from the cronjob.
The code has a line:
aws s3 cp s3://My/files/backup/ ~/home/AnPoc/ --recursive --exclude "*.tgz" --include "*results.tgz"
And in the email I recieve from the cronjob execution, I see the following error message:
./AnPoc/DayProcessing.sh: line 14: aws: command not found
I don't know why the command is not being found. Any help would be great.
|
AWS not working working from Cronjob
|
This is a general implementation, which lets you set:
interval period
hour to tick
minute to tick
second to tick
UPDATED: (the memory leak was fixed)
import (
"fmt"
"time"
)
const INTERVAL_PERIOD time.Duration = 24 * time.Hour
const HOUR_TO_TICK int = 23
const MINUTE_TO_TICK int = 00
const SECOND_TO_TICK int = 03
type jobTicker struct {
timer *time.Timer
}
func runningRoutine() {
jobTicker := &jobTicker{}
jobTicker.updateTimer()
for {
<-jobTicker.timer.C
fmt.Println(time.Now(), "- just ticked")
jobTicker.updateTimer()
}
}
func (t *jobTicker) updateTimer() {
nextTick := time.Date(time.Now().Year(), time.Now().Month(),
time.Now().Day(), HOUR_TO_TICK, MINUTE_TO_TICK, SECOND_TO_TICK, 0, time.Local)
if !nextTick.After(time.Now()) {
nextTick = nextTick.Add(INTERVAL_PERIOD)
}
fmt.Println(nextTick, "- next tick")
diff := nextTick.Sub(time.Now())
if t.timer == nil {
t.timer = time.NewTimer(diff)
} else {
t.timer.Reset(diff)
}
}
|
I have been looking around for examples on how to implement a function that allows you to execute tasks at a certain time in Go, but I couldn't find anything.
I implemented one myself and I am sharing it in the answers, so other people can have a reference for their own implementation.
|
Golang: Implementing a cron / executing tasks at a specific time
|
In SSMS navigate to SQL Server Agent-->Jobs
Right click on the Job Folder and select new job
on the dialog that pops up, give the job a name
click on steps, then on new, you will see a dialog like the following, pick correct DB and type your proc name
after that click on schedule, pick new and you will see something like the image below, fill all the stuff you need and click ok, click ok on the job and you should be set
|
I have a table on which I want to perform some operations every hour. For this I created a Stored Procedure but don't know how to call it every hour. I know there are some kind of scheduled jobs, but how to use them.
Is there some kind of service also that keeps on running continuously, every second, where I can place my piece of code to be executed ?
|
How to run a stored procedure in sql server every hour?
|
If you have PHP installed as a command line tool (try issuing php to the terminal and see if it works), your shebang (#!) line needs to look like this:
#!/usr/bin/php
Put that at the top of your script, make it executable (chmod +x myscript.php), and make a Cron job to execute that script (same way you'd execute a bash script).
You can also use php myscript.php.
|
I have a php script that I want to be run using a bash script, so I can use Cron to run the php script every minute or so.
As far as I'm aware I need to create the bash script to handle the php script which will then allow me to use the Cron tool/timer.
So far I was told I need to put:
#!/pathtoscript/testphp.php
at the start of my php script. Im not sure what to do from here...
Any advice? Thanks.
|
Bash script to run php script
|
When you run ssh-agent -s, it launches a background process that you'll need to kill later. So, the minimum is to change your hack to something like:
eval `ssh-agent -s`
svn stuff
kill $SSH_AGENT_PID
However, I don't understand how this hack is working. Simply running an agent without also running ssh-add will not load any keys. Perhaps MacOS' ssh-agent is behaving differently than its manual page says it does.
|
I wrote a simple script which mails out svn activity logs nightly to our developers. Until now, I've run it on the same machine as the svn repository, so I didn't have to worry about authentication, I could just use svn's file:/// address style.
Now I'm running the script on a home computer, accessing a remote repository, so I had to change to svn+ssh:// paths. With ssh-key nicely set up, I don't ever have to enter passwords for accessing the svn repository under normal circumstances.
However, crontab did not have access to my ssh-keys / ssh-agent. I've read about this problem a few places on the web, and it's also alluded to here, without resolution:
Why ssh fails from crontab but succedes when executed from a command line?
My solution was to add this to the top of the script:
### TOTAL HACK TO MAKE SSH-KEYS WORK ###
eval `ssh-agent -s`
This seems to work under MacOSX 10.6.
My question is, how terrible is this, and is there a better way?
|
ssh-agent and crontab -- is there a good way to get these to meet?
|
Perhaps the python package croniter suits your needs.
Usage example:
>>> import croniter
>>> import datetime
>>> now = datetime.datetime.now()
>>> cron = croniter.croniter('45 17 */2 * *', now)
>>> cron.get_next(datetime.datetime)
datetime.datetime(2011, 9, 14, 17, 45)
>>> cron.get_next(datetime.datetime)
datetime.datetime(2011, 9, 16, 17, 45)
>>> cron.get_next(datetime.datetime)
datetime.datetime(2011, 9, 18, 17, 45)
|
I need to parse a crontab-like schedule definition in Python (e.g. 00 3 * * *) and get where this should have last run.
Is there a good (preferably small) library that parses these strings and translates them to dates?
|
Parsing crontab-style lines
|
Did you try running command manually?
Run php artisan and see if your commands have registered.
If you have registered your commands you should see command:daily-reset and command:monthly-reset under the list of available artisan commands.
If you don't see them there go ahead and register your commands by adding it to commands property available in app/Console/Kernel.php.
protected $commands = [
'App\Console\Commands\YourFirstCommand',
'App\Console\Commands\YourSecondCommand'
];
Change crontab entry to
* * * * * php /home/privates/public_html/staging/current/artisan schedule:run
|
I've set up the following Laravel commands on the App\Console\Kernel:
protected function schedule(Schedule $schedule) {
$schedule->command('command:daily-reset')->daily();
$schedule->command('command:monthly-reset')->monthly();
}
Then, on my server, I've set up a cron job to run once per day (at 00:00).
0 0 * * * php /home/privates/public_html/staging/current/artisan schedule:run
My cron job is running successfully each night, but the logs simply say: "No scheduled commands are ready to run."
What am I doing wrong? I would expect my daily command to run each night.
Thanks!
|
Laravel "No scheduled commands are ready to run."
|
From here:
Cron also supports 'step' values.
A value of */2 in the dom field would
mean the command runs every two days
and likewise, */5 in the hours field
would mean the command runs every 5
hours. e.g.
* 12 10-16/2 * * root backup.sh
is the same as:
* 12 10,12,14,16 * * root backup.sh
So I think you want 0 0 */2 * *.
What you've got (0 0 2 * *) will run the command on the 2nd of the month at midnight, every month.
p.s. You seem to have an extra asterisk in your answer. The format should be:
minute hour dom month dow user cmd
So your extra asterisk would be in the user field. Is that intended?
|
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 4 years ago.
Improve this question
We would like to use a cronjob to create a database backup.
The backup should occur ones every two days. Can the following cron-entry be used?
0 0 2 * * * backup-command
If this is wrong please tell me the correct command for setting the cron for 2 days.
|
how to set cronjob for 2 days? [closed]
|
61
You can use TimerTask for Cronjobs.
Main.java
public class Main{
public static void main(String[] args){
Timer t = new Timer();
MyTask mTask = new MyTask();
// This task is scheduled to run every 10 seconds
t.scheduleAtFixedRate(mTask, 0, 10000);
}
}
MyTask.java
class MyTask extends TimerTask{
public MyTask(){
//Some stuffs
}
@Override
public void run() {
System.out.println("Hi see you after 10 seconds");
}
}
Timer
TimerTask
Alternative
You can also use ScheduledExecutorService.
Share
Improve this answer
Follow
edited Sep 23, 2014 at 16:34
answered Sep 22, 2014 at 10:28
IndrajithIndrajith
8801212 silver badges2121 bronze badges
1
1
Another alternative is JobRunr: it allows to run CRON jobs using a annotation if you are using Spring Framework or Micronaut: @Recurring(id = "my-recurring-job", cron = "*/5 * * * *")
– rdehuyss
Apr 26, 2022 at 6:43
Add a comment
|
|
This question already has answers here:
How to run a Java program under cron and import the jars
(3 answers)
Closed 8 years ago.
I'm writing a standalone batch Java application to read data from YouTube. I want to set up an cron job to do certain job every hour.
I search and found ways to do a cron job for basic operations but not for a Java application.
|
How to create a Java cron job [duplicate]
|
90
Poll SCM periodically polls the SCM to check whether changes were made (i.e. new commits) and builds the project if new commits where pushed since the last build, whereas build periodically builds the project periodically even if nothing has changed.
Share
Improve this answer
Follow
answered Dec 13, 2016 at 5:33
tkausltkausl
13.9k22 gold badges3434 silver badges5252 bronze badges
1
1
what happens if we dont mention any cron expression in poll scm ? does it poll scm ?
– chandu_reddim
Dec 2, 2021 at 9:29
Add a comment
|
|
In both it takes cron expression as input, so what's the actual difference between these two.
|
What is the difference between Poll SCM & build periodically in Jenkins?
|
It depends.
From https://www.php.net/manual/en/features.connection-handling.php:
When a PHP script is running normally
the NORMAL state, is active. If the
remote client disconnects the ABORTED
state flag is turned on. A remote
client disconnect is usually caused by
the user hitting his STOP button.
You can decide whether or not you want
a client disconnect to cause your
script to be aborted. Sometimes it is
handy to always have your scripts run
to completion even if there is no
remote browser receiving the output.
The default behaviour is however for
your script to be aborted when the
remote client disconnects. This
behaviour can be set via the
ignore_user_abort php.ini directive as
well as through the corresponding
php_value ignore_user_abort Apache
httpd.conf directive or with the
ignore_user_abort() function.
That would seem to say the answer to your question is "Yes, the script will terminate if the user leaves the page".
However realize that depending on the backend SAPI being used (eg, mod_php), php cannot detect that the client has aborted the connection until an attempt is made to send information to the client. If your long running script does not issue a flush() the script may keep on running even though the user has closed the connection.
Complicating things is even if you do issue periodic calls to flush(), having output buffering on will cause those calls to trap and won't send them down to the client until the script completes anyway!
Further complicating things is if you have installed Apache handlers that buffer the response (for example mod_gzip) then once again php will not detect that the connection is closed and the script will keep on trucking.
Phew.
|
I want to run a relatively time consuming script based on some form input, but I'd rather not resort to cron, so I'm wondering if a php page requested through ajax will continue to execute until completion or if it will halt if the user leaves the page.
It doesn't actually output to the browser until a json_encode at the end of the file, so would everything before that still execute?
|
Does php execution stop after a user leaves the page?
|
0/1 means start at hour 0 and repeat each 1 hour
1/1 is start first day of the month and execute each 1 day
So this pattern executes the cron once each hour, starting day one of month and repeating itself every day.
there is a requirement to use ? in one of dayOfWeek or dayOfMonth:
Support for specifying both a day-of-week and a day-of-month value is not complete (you must currently use the ‘?’ character in one of these fields). – xenteros 7 mins ago
Then, 0 0 * * * ? * (and not 00, with 01 mandatory as you commented) will be same expression, ignoring seconds and minutes and taking each value of other elements, will execute each hour and everyday.
According your information:
02
And this explanation of the special characters:
03 (“all values”)
used to select all values within a field. For example, “” in the minute field means *“every minute”.
04 (“no specific value”)
useful when you need to specify something in one of the two fields in which the character is allowed, but not the other. For example, if I want my trigger to fire on a particular day of the month (say, the 10th), but don’t care what day of the week that happens to be, I would put “10” in the day-of-month field, and “?” in the day-of-week field.
05
used to specify increments. For example, “0/15” in the seconds field means “the seconds 0, 15, 30, and 45”. And “5/15” in the seconds field means “the seconds 5, 20, 35, and 50”. You can also specify ‘/’ after the ‘’ character - in this case ‘’ is equivalent to having ‘0’ before the ‘/’. ‘1/3’ in the day-of-month field means “fire every 3 days starting on the first day of the month”.
differences between 06 and 07
To explain difference between 08 and 09 in the expressions, first of all take a look at this table:
10
As you can see 11 is only allowed in 12 and 13 is mandatory in one of both fields and will tell Quartz this value has not been defined, thus, use the other field (if you put 14 into 15, the value used will be 16).
|
I have the following cron expression in my system:
0 0 0/1 1/1 * ? *
and you know what? I have no idea what it means. The guy who has written it is on his holiday for the next 2 weeks so I have to find out on myself. The documentation can be found here
According to the documentation we have:
* * * * * * *
| | | | | | |
| | | | | | +-- Year (range: 1970-2099)
| | | | | +---- Day of the Week (range: 1-7 or SUN-SAT)
| | | | +------ Month of the Year (range: 0-11 or JAN-DEC)
| | | +-------- Day of the Month (range: 1-31)
| | +---------- Hour (range: 0-23)
| +------------ Minute (range: 0-59)
+-------------- Second (range: 0-59)
Ok, let me tell you what I think: I believe that the expression means:
start when:
seconds: 0
minutes: 0
hours: 0
dayOfMonth 1
monthOfYear any
dayOfWeek any
year any
run every:
1 hour
1 dayOfWeek
when:
dayOfWeek same as on first execution
However available cron expression monitors says that it simply means every hour.
As the one who has written that is Senior Java Dev, he must have known any reason for writing such expression instead of:
0 0 * * * * *
We use org.springframework.scheduling.quartz.QuartzJobBean.
Short summary
Well, I think that my question is: what is the difference between 0 0 0/1 1/1 * ? * and 0 0 * * * * *?
Edit:
The documentation can be found here.
|
Is there a difference between ? and * in cron expressions? Strange example
|
92
1 Seconds
2 Minutes
3 Hours
4 Day-of-Month
5 Month
6 Day-of-Week
7 Year (optional field)
So in your case:
0 0 0 * * ?
This will fire at midnight, if you want to fire at noon:
0 0 12 * * ?
Or both:
0 0 0,12 * * ?
A good page if you want to get more complicated: http://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/tutorial-lesson-06
Have an awesome day!
Share
Improve this answer
Follow
edited Jul 17, 2016 at 8:52
answered Jun 21, 2012 at 21:06
S..S..
5,58822 gold badges3838 silver badges4343 bronze badges
Add a comment
|
|
What is the cron expression in Quartz Scheduler to run a program at 12 am every midnight GMT.
I have never used quartz before so I am still learning.
Is the expression 0 0 12 * * ? or is that for 12 pm (noon). Could anyone tell me?
|
Cron Expression (Quartz) for a program to run every midnight at 12 am
|
As of Spring 5.1.0 the @Scheduled annotation can accept "-" as the cron expression to disable the cron trigger.
Per the Javadocs:
The special value "-" indicates a disabled cron trigger, primarily meant for externally specified values resolved by a ${...} placeholder.
|
My application loads some cron patterns from a properties file. I'm using the @Scheduled annotation like this:
@Scheduled(cron = "${config.cronExpression:0 0 11,23 * * *}")
Now I want to disable some tasks and the easiest solution would be to enter a cron pattern which will never run.
In order to do this, I thought about using a cron expression that only executes at a specific day in the past.
But unfortunately the Spring cron expressions don't allow to add a year or a date in the past.
Is there any pattern that will never run?
|
Spring Cron scheduler “disable pattern”
|
You want to edit your crontab file using
crontab -e
Then you want to add
55 23 * * * COMMAND TO BE EXECUTED
for more info look at this
|
This question already has answers here:
How to write a cron that will run a script every day at midnight?
(6 answers)
Closed 8 years ago.
I have a simple shell script that just checks the contents of a directory and if anything was added during the day makes a copy of it to a backup folder.
I'd like to execute this script at the end of each day (let's assume at 23:55).
The system(Debian) which this scripts reside on it, is always on (kind of server)
How can I do that?
|
Execute a shell script everyday at specific time [duplicate]
|
Can't you simply create a trigger without actually executing it? You could simply give appropriate feedback in case of a ParseException. If the expression is okay, persist the expression to DB.
Edit: or simply do this:
org.quartz.CronExpression.isValidExpression(expression);
|
I'm writing a scheduling application in Java using Quartz. I'm using the CronTrigger, but my cron expressions are entered into a database before they are scheduled and are based on user input.
Is there a way I can verify that the cron expressions are valid when I capture them? I'd rather do this and give the user an appropriate error message than wait until the scheduler is run and I get a ParseException when I try and create the trigger. Which could be days after the user inputs the data.
|
Verifying a cron expression is valid in Java
|
True solution for OSX
Write the following function to your ~/.bashrc or ~/.zshrc.
capture() {
sudo dtrace -p "$1" -qn '
syscall::write*:entry
/pid == $target && arg0 == 1/ {
printf("%s", copyinstr(arg1, arg2));
}
'
}
Usage:
example@localhost:~$ perl -e 'STDOUT->autoflush; while (1) { print "Hello\n"; sleep 1; }' >/dev/null &
[1] 97755
example@localhost:~$ capture 97755
Hello
Hello
Hello
Hello
...
https://github.com/mivok/squirrelpouch/wiki/dtrace
NOTE:
You must disable dtrace restriction on El Capitan or later.
csrutil enable --without dtrace
|
I have a running cron job that will be going for a while and I'd like to view its stdout. I don't know how important the fact that the process was started by cron is, but I figure I'd mention it. This is on OSX so, I don't have access to things like... /proc/[pid]/..., or truss, or strace. Suggestions of executing with IO redirection (e.g. script > output & tail -f output) are NOT acceptable, because this process is 1) already running, and 2) can't be stopped/restarted with redirection. If there are general solutions that will work across various Unices, that'd be ideal, but specifically I'm trying to accomplish this on a Mac right now.
|
How can I capture the stdout from a process that is ALREADY running
|
It's the other way around:
*/1 * * * * sudo /home/pi/coup/sensor.py >> /home/pi/sensorLog.txt 2>&1
2>&1 will redirect standard error (2) to standard output (1) which -in turn - was redirected to your log file. So, at the end, both stderr and stdout will go to your sensorLog.txt
|
I've got a cron job that is set up like this in my crontab:
*/1 * * * * sudo /home/pi/coup/sensor.py >> /home/pi/sensorLog.txt
It puts stdout into sensorLog.txt, and any stderr it generates gets put into an email.
I want both stdout and stderr to go into sensorLog.txt, so I added 1>&2 to the crontab, which is supposed to make stderr go into the same place as stdout. It now looks like this:
*/1 * * * * sudo /home/pi/coup/sensor.py >> /home/pi/sensorLog.txt 1>&2
Now, both stdout and stderr both get put into an email, and nothing gets added to the file. This is the opposite of what I am trying to accomplish.
How do I get both stdout and stderr to get redirected to the file?
|
How to redirect stderr to a file in a cron job
|
May be it is, cron jobs will run in their own shell. So you can't expect to see asdf on your console.
What you should try is
* * * * * echo asdf > somefile_in_your_home_directory_with_complete_path.log
Next check the file by doing a tail:
tail -f somefile_in_your_home_directory_with_complete_path.log
And if it's not, check if the cron daemon itself is running or is down:
# pgrep crond
OR
# service crond status
|
I've got such situation:
I want to schedule a job with crontab on a linux server. I'm not super-user, so I'm editing (with crontab -l, editor vim) only my crontab file. For testing, I put there:
* * * * * echo asdf
And the job is not running. Is the restart of the server needed? Or maybe some administrator move?
|
Crontab - simple echo not running
|
98
Whenever doesn't detect your environment, it just defaults to using production.
You can set the environment for all jobs using set:
set :environment, 'staging'
Or per job:
every 2.hours do
runner 'My.runner', :environment => 'staging'
end
Share
Improve this answer
Follow
edited Jan 30, 2013 at 19:37
AJcodez
32.7k2020 gold badges8585 silver badges118118 bronze badges
answered Sep 3, 2010 at 14:22
Trung LETrung LE
98166 silver badges22 bronze badges
3
5
can I pass an array to the environment hast to set multiple environments?
– mrudult
Feb 27, 2014 at 12:23
This is not the correct way when we are dealing with multiple environments
– Franchy
Jul 29, 2019 at 22:16
What is the correct way when we are dealing with multiple environments?
– Leland Reardon
May 2, 2022 at 3:17
Add a comment
|
|
This question will probably only make sense if you know about the whenever gem for creating cron jobs. I have a task in my schedule.rb like
every 1.day, :at => '4am' do
command "cd #{RAILS_ROOT} && rake thinking_sphinx:stop RAILS_ENV=#{RAILS_ENV}"
command "cd #{RAILS_ROOT} && rake thinking_sphinx:index RAILS_ENV=#{RAILS_ENV}"
command "cd #{RAILS_ROOT} && rake thinking_sphinx:start RAILS_ENV=#{RAILS_ENV}"
end
However when I update my crontab using
whenever --update-crontab appname --set environment=production
the cron jobs still have RAILS_ENV=development. My tasks on production and development are the same right now, I just need to change the environment variable because thinking_sphinx needs to know the current environment. Any ideas on how to do this?
Thanks!
|
Rails cron with whenever, setting the environment
|
cron is the name of the tool, crontab is generally the file that lists the jobs that cron will be executing, and those jobs are, surprise surprise, cronjobs.
|
Technically speaking, what is the difference between a cron, crontab, and cronjob?
From what I can gather, cron is the utility on the server, crontab is a file which contains the time intervals and commands, and cronjob is the actual command (or file/script which contains commands).
Is this correct?
|
Difference between cron, crontab, and cronjob?
|
to check if cron is actually running anything at this moment in time (works on ubuntu)
pstree -apl `pidof cron`
and you'll either get
2775,cron # your pid (2775) will be different to mine :-)
or a tree output with all the child processes that cron is running (it may not name them if you don't have sufficient privileges)
and as Hamoriz says the logs are in /var/log/syslog so
grep CRON /var/log/syslog
will get you the logs just for cron
|
I have a cron job set up for daily execution (on my own ubuntu, just for trial) like so:
0 0 * * * /path/exec.sh
It is been set for daily execution. I usually open my machine around 8a.m. I would like to find out
- what time my cron job ran, if it has already run ?
- I would also like to see if any of my cron job is running at the moment?
Is there a way to find out IF a cron job is actually running at the moment?
|
How to view a cron job running currently?
|
It's stored in the database inside wp_options under the option_name cron.
You can get the array with: _get_cron_array() or get_option('cron').
See: http://core.trac.wordpress.org/browser/trunk/wp-includes/cron.php
|
I was looking in wp_options table but there is nothing like that eventhough I have set my cron tasks like:
add_action('init', function() {
if ( !wp_next_scheduled('my_awesome_cron_hook') ) {
wp_schedule_event(time(), 'hourly', 'my_awesome_cron_hook');
}
});
Or is it stored in some txt file in wordpress?
|
Where in Wordpress DB are stored wp_cron tasks?
|
116
You need to escape % character with \
mysqldump -u 'username' -p'password' DBNAME > /home/eric/db_backup/liveDB_`date +\%Y\%m\%d_\%H\%M`.sql
Share
Improve this answer
Follow
answered Jun 16, 2014 at 2:41
The Java GuyThe Java Guy
2,14111 gold badge1515 silver badges1212 bronze badges
8
14
I would like to vote +10! No other source than this (many Google results, websites, forum posts) have given me this result, this was the solution for me. Without this answer, I would have searched for hours...
– Basj
Sep 21, 2016 at 7:47
4
one mistake I made was to leave a space between -p and my password, there should be no space i.e -pPASSWORD
– Manny265
Nov 23, 2016 at 9:05
1
@Basj: what if I searched for hours until I found this answer? mind blown
– Benoit Duffez
Apr 21, 2017 at 7:21
1
Very useful your answer. Thanks so much. After to escape % character with \ , it works fine. Thanks @Sandeep
– Geraldo Novais
Jul 15, 2017 at 2:32
1
This was my problem as well; if you follow one of the first Google links about "Backing up MySQL on Centos", they do not include the \
– tsumnia
Oct 13, 2018 at 15:30
|
Show 3 more comments
|
I'm trying to add a cronjob in the crontab (ubuntu server) that backups the mysql db.
Executing the script in the terminal as root works well, but inserted in the crontab nothing happens. I've tried to run it each minutes but no files appears in the folder /var/db_backups.
(Other cronjobs work well)
Here is the cronjob:
* * * * * mysqldump -u root -pHERE THERE IS MY PASSWORD
--all-databases | gzip > /var/db_backups/database_`date +%d%m%y`.sql.gz
what can be the problem?
|
mysqldump doesn't work in crontab
|
I got it and give you step by step adding cron jobs into your system:
Login to your server with SSH
Type crontab -l to display list of cron jobs,
Type crontab -e to edit your crontab,
Add 0 4 * * * /etc/init.d/mysqld restart to restart Mysql everyday at 4 AM,
Add 0 5 * * * /etc/init.d/httpd restart to restart Apache everyday at 5 AM and
Add 0 24 * * * /etc/init.d/httpd restart to restart Apache everyday at 12 AM
Save your file,
Recheck with crontab -l
|
I have a CentOs setup in test server.
I wanna to run a cron job (the cron needs to run apache server at 12AM) daily.
My cron.daily fodler is located in /etc/cron.daily
Please let me know the steps how to implement this.
Usually I use to restart the apache service using the below command:
service httpd restart
I wanna to do restart apache service automatically using cron 12AM daily.
Thanks in advance.
|
restart apache service automatically using cron 12AM daily
|
test.php:
<?php
print_r($argv);
?>
Shell:
$ php -q test.php foo bar
Array
(
[0] => test.php
[1] => foo
[2] => bar
)
|
I need to execute a php file with parameters through shell.
here is how I would run the php file:
php -q htdocs/file.php
I need to have the parameter 'show' be passed through and
php -q htdocs/file.php?show=show_name
doesn't work
If someone could spell out to me what command to execute to get the php file to execute with set parameters, it would be much appreciated. If not, try to lead me the right direction.
|
Shell run/execute php script with parameters
|
The short answer is that you have to set the DISPLAY environment variable, and then the app will run.
The long answer is that we've got Xauth, and unless you're running as the same user on the same machine that's probably not going to work unless you export the Xauth credential from the account running the X server to the account running the X client. ssh -X handles this for you, which is why it's awesome, but the manual procedure involves running xauth extract - $DISPLAY on the X server account and feeding that data into xauth merge - on the client account. (Warning: the data is binary.)
On modern Linux systems, there is one X session at :0 and the X11 authority data file is always $HOME/.Xauthority so you can most often set two environment variables, for example, in Bash:
export XAUTHORITY=/home/$your_username/.Xauthority
export DISPLAY=':0'
|
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 10 years ago.
Improve this question
Without being the person logged in at the console, how do I run an X application and have it display on that X session? Assume I am either root, or I am the same user who logged in, so in principle I have persmission to do this. But how do I convince X of this?
Some examples of situations like this:
Log in with SSH and run a program that displays on the remote computer's screen (not tunneled through SSH—that is totally different)
A cron job to take a screenshot of the X session via ImageMagick's import command
Running a keystroke logger for audit purposes
This is a simpler version of Launch OpenGL app straight from a windowless Linux Terminal
|
How to run an X program from outside the X session (e.g. from the console or SSH) [closed]
|
I've found a solution to load rbenv. Either with a loader importing rbenv to the PATH :
*/1 * * * * /bin/bash -c '. $HOME/.rbenv/loader.sh ; cd /data/app/; ruby -v'
The '.' before '$HOME/.rbenv/loader.sh' is important, it runs the script in the current shell
Or without loader, which is better :
*/1 * * * * /bin/bash -c 'export PATH="$HOME/.rbenv/bin:$PATH" ; eval "$(rbenv init -)"; cd /data/app/; ruby -v'
|
I'm trying to run a Ruby script using rbenv with cron.
I know that I need to load rbenv in order to have the right Ruby version loaded.
I've tried options like this:
*/10 * * * * /bin/bash -c 'source $HOME/.bashrc; cd /data/app; ruby -v' >> /tmp/logfile.txt 2>&1
but as the session is not interactive, I'm not having the right Ruby version.
I've found example like this:
15 14 1 * * export BASH_ENV=/path/to/environment && /full/path/to/bash -c '/full/path/to/rvm_script.rb'
It didn't work neither. Then I wrote a loader, which only load rbenv in the current shell but it doesn't work.
*/1 * * * * /bin/bash -c '$HOME/.rbenv/loader.sh ; cd /data/app/; ruby -v ' >> /tmp/logfile.txt 2>&1
Now I'm searching for another way to load it ... any ideas?
|
How to run a Ruby script using rbenv with cron
|
you can add a bean to get cron value from database in the SpringBootApplication main class or in any of the configuration class. Example code is below:
@Autowired
private CronRepository cronRepo;
@Bean
public int getCronValue()
{
return cronRepo.findOne("cron").getCronValue();
}
you should create a table and provide suitable values in the database. After that you can provide the bean inside the @Scheduled. Example code is below:
@Scheduled(cron="#{@getCronValue}")
Hope it works for your issue.
|
I'm using Spring Boot and have issues scheduling a cron task using values existing in database.
For the time being, I'm reading values from properties file like below :
@Scheduled(cron= "${time.export.cron}")
public void performJob() throws Exception {
// do something
}
This works nicely, but instead of getting values from properties file, I want to get them from database table. Is it possible and how ?
|
Spring Boot : Getting @Scheduled cron value from database
|
You can run cron without daemon mode.
root@xxxxxx:~# cron -f
I was just trying to test it:
I started /bin/bash in a new container
apt-get install cron nano screen
getty tty -a root
screen, in screen I created 2 terminals:
first: cron -f
second: crontab -e - edit your crontab, save and you can watch that the cron is working ...
|
I have installed cron via apt-get install cron
Trying to start cron fails (as expected) because of upstart not running.
What is the command line for starting cron properly (i.e. it will read users' crontabs, will read /etc/crontab/* etc)?
Please note that I do not want to start the container as a "full" machine, so I don't want to run /sbin/init or upstart. I manage the processes via supervisord, so what I 'm missing is the command line to add to its configuration file.
|
How do I start cron on docker ubuntu base?
|
The H will take a numeric hash of the Job name and use this to ensure that different jobs with the same cron settings do not all trigger at the same time. This is a form of Scheduling Jitter
H/5 in the first field means Every five minutes starting at some time between 0 and 4 minutes past the hour
So H/5 3,21 * * 1-5
is Every five minutes between 03:00 and 03:59 and then between 21:00 and 21:59 on Mon -> Fri but starting at some 'random' time between 03:00 and 03:04 and then the same number of minutes after 21:00
If you want to run once per hour between 03:00-03:59 and 21:00-21:59 on Mon -> Fri, you can use H 3,21 * * 1-5 where H will be replaced by some number between 0-59 depending on job name.
The user interface will tell you when the job will last have triggered and will next trigger
|
I have a job with as cron:
5 3,21 * * 1-5
This will run my job at 03:05AM and 09:05PM. Now I read it's a best practice to use H.
I try:
H/5 3,21 * * 1-5
What is the meaning now? Will this schedule a build in a range of 5 minutes or 5 minutes after 3AM and 21PM?
|
Meaning of H/5 in cron Jenkins
|
Try Quartz.NET. It's a decent .NET scheduler which supports CRON expressions, CRON triggers and various other means and methods to schedule tasks to be performed at certain times / intervals.
It even includes a basic Quartz.NET server (Windows Application) that might fit your needs.
Edit:
If you can't run applications or windows services within your shared hosting then perhaps something like "Easy Background Tasks in ASP.NET" will do you? It simulates a Windows Service using HttpRuntime.Cache and removes the need for any external dependancies.
|
In PHP we have cron jobs, where the hosting server automatically picks up and executes a task as per the schedule given.
What would be a good alternative to use for CRON jobs in ASP.NET? I'd like to use a Web service, but that will not work in a shared hosting environment. Any help would be appreciated, and please advise a way to do this specifically in a shared hosting environment.
|
What is the equivalent to cron jobs in ASP.NET?
|
Crontab doesn't remember what time you "started" (presumably the time you executed the crontab -e or crontab filename command).
If you want to run the job every 15 minutes starting from an arbitrary time, you'll have to specify that time. This:
7-59/15 * * * * command
will run at 7, 22, 37, and 52 minutes after each hour. That's assuming you're running Vixie cron, which is the most common implementation. For better portability, you can use:
7,22,37,52 * * * * command
And remember that you can't have spaces within any of the first 5 fields; 0, 15,30,45, as you had in your question, is invalid.
|
I'm trying to get a simple crontab job to run every 15 minutes and am having trouble deciding how to format the timing.
What I've been putting down is the following:
15 * * * * ------------------------
I'm pretty sure this just runs the first 15 minutes of every hour.
I think that crontab allows users to specify exact times to run, namely:
0, 15,30,45 * * * * -------------------------
But if I wanted to run the crontab every 15 minutes from the moment I start it, (which may not necessarily be on a value divisible by 15), how would I go about formatting that/is that possible?
|
Crontab Formatting - every 15 minutes
|
you can try "tty" to see if it's run by a terminal or not. that won't tell you that it's specifically run by cron, but you can tell if its "not a user as a prompt".
you can also get your parent-pid and follow it up the tree to look for cron, though that's a little heavy-handed.
|
Not having much luck Googling this question and I thought about posting it on SF, but it actually seems like a development question. If not, please feel free to migrate.
So, I have a script that runs via cron every morning at about 3 am. I also run the same scripts manually sometimes. The problem is that every time I run my script manually and it fails, it sends me an e-mail; even though I can look at the output and view the error in the console.
Is there a way for the bash script to tell that it's being run through cron (perhaps by using whoami) and only send the e-mail if so? I'd love to stop receiving emails when I'm doing my testing...
|
Can a bash script tell if it's being run via cron?
|
Which version of spring framework are you using? This won't work if it is less than 3.0.1.
Bug Report here in Spring 3.0.0 and it has been fixed in 3.0.1.
So if you are using Spring 3.0.1 or greater then following things you have to do to use in cron expression
Make an entry in applicationContext.xml for PropertyPlaceHolderConfigurer class that is
<bean id="placeholderConfig"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:ApplicationProps.properties</value>
</list>
</property>
</bean>
After That Use it in using the @Scheduled method like
Update: In case if you are using spring boot no need to do anything, below code excerpt should work.
@Scheduled(cron="${instructionSchedularTime}")
public void load(){
}
Note: fixed delay and fixed-rate cann't take property value from placeholder because they take long value. Cron attribute take argument as String so you can use placeholder for that.
|
I have written a cron job:
@Scheduled(cron="${process.virtual.account.start}")
public void ecomProcessVirAccOrderPaymentsScheduler() {
LOGGER.info("Start --->" + this.getClass().getCanonicalName() + ".ecomProcessVirAccOrderPaymentsScheduler() Method");
schedulerJobHelper.ecomProcessVirAccOrderPaymentsScheduler();
LOGGER.info("End --->" + this.getClass().getCanonicalName() + ".ecomProcessVirAccOrderPaymentsScheduler() Method");
}
I want to get the cron attribute used with @Scheduled annotation to be populated from a external properties file. Currently I am fetching it from a property file inside the application scope.
I am able to fetch the value, but not able to use it with @Schedule annotation.
|
Task scheduling using cron expression from properties file
|
There's special standard module for this task - Sites Framework.
It adds Site model, which describes specific site. This model has field domain for domain of the project, and a name - human-readable name of the site.
You associate your models with sites. Like so:
from django.db import models
from django.contrib.sites.models import Site
class Article(models.Model):
headline = models.CharField(max_length=200)
# ...
site = models.ForeignKey(Site, on_delete=models.CASCADE)
When you need to make an url for the object you may use something like the following code:
>>> from django.contrib.sites.models import Site
>>> obj = MyModel.objects.get(id=3)
>>> obj.get_absolute_url()
'/mymodel/objects/3/'
>>> Site.objects.get_current().domain
'example.com'
>>> 'https://%s%s' % (Site.objects.get_current().domain, obj.get_absolute_url())
'https://example.com/mymodel/objects/3/'
This way you can have multiple domains and content spread between them.
Even if you have only one domain I recommend use it to achieve a good standard comfortable way to keep domain settings.
Installatioin is quite easy:
Add 'django.contrib.sites' to your INSTALLED_APPS setting.
Define a SITE_ID setting:
SITE_ID = 1
Run migrate.
|
I want to send mails in a cron job. The mail should contain
a link to my application.
In cron job, I don't have a request object, and can't use request.build_absolute_uri().
AFAIK the site framework can help here. But does not give me the protocol (http vs https)?
My application is reusable and sometimes gets hosted on http and sometimes on https sites.
Update
I search a common django way. Creating custom settings is possible, but a solution with django standards is preferred.
|
How can I get the URL (with protocol and domain) in Django (without request)?
|
Advisory locking is made for exactly this purpose.
You can accomplish advisory locking with flock(). Simply apply the function to a previously opened lock file to determine if another script has a lock on it.
$f = fopen('lock', 'w') or die ('Cannot create lock file');
if (flock($f, LOCK_EX | LOCK_NB)) {
// yay
}
In this case I'm adding LOCK_NB to prevent the next script from waiting until the first has finished. Since you're using cron there will always be a next script.
If the current script prematurely terminates, any file locks will get released by the OS.
|
I have one php script, and I am executing this script via cron every 10 minutes on CentOS.
The problem is that if the cron job will take more than 10 minutes, then another instance of the same cron job will start.
I tried one trick, that is:
Created one lock file with php code (same like pid files) when
the cron job started.
Removed the lock file with php code when the job finished.
And when any new cron job started execution of script, I checked if lock
file exists and if so, aborted the script.
But there can be one problem that, when the lock file is not deleted or removed by script because of any reason.
The cron will never start again.
Is there any way I can stop the execution of a cron job again if it is already running, with Linux commands or similar to this?
|
How to prevent the cron job execution, if it is already running
|
They'll run at the same time. The standard practice around this is to create a file lock (commonly referred to as a flock), and if the lock isn't available, don't run.
The advantages to this over Zdenek's approach is that it doesn't require a database, and when the process ends, the flock is automatically released. This includes cases where the the process is killed, server rebooted, etc.
While you don't mention what your cron job is written in, flock is standard in most languages. I'd suggest googling for locks and the language you're using, as this will be the more robust solution, and not relying upon random timeouts. Here are some examples from SO:
Shell script
Python
PHP
Perl
|
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to prevent the cron job execution, if it is already running
I have a cron job that may take 2 mins or may take 5 hours to complete.
I need to make sure that this job is always executed.
My question is:
Will it start after the previous one is done or will they both run at the same time and mess up the database if i set it to execute every minute ?
|
Will Cron start a new job if the current job is not complete? [duplicate]
|
45
That's not possible with a single expression in normal cron.
The best you could do without modifying the code is:
0 0,3,6,9,12,15,18,21 * * * [cmd]
30 1,4,7,10,13,16,19,22 * * * [cmd]
These might be compressible, depending on the version of cron you have to:
0 */3 * * * [cmd]
30 1-23/3 * * * [cmd]
Share
Improve this answer
Follow
edited Oct 26, 2020 at 13:22
answered Oct 29, 2008 at 17:17
AlnitakAlnitak
337k7070 gold badges411411 silver badges496496 bronze badges
Add a comment
|
|
How can I set cron to run certain commands every one and a half hours?
|
How can I set cron to run certain commands every one and a half hours?
|
It means that the task is taking longer than one second and by default only one concurrent execution is allowed for a given job. I cannot tell you how to handle this without knowing what the task is about.
|
I am executing a function every second using Python apscheduler (version 3.0.1)
code:
scheduler = BackgroundScheduler()
scheduler.add_job(runsync, 'interval', seconds=1)
scheduler.start()
It's working fine most of the time but sometimes I get this warning:
WARNING:apscheduler.scheduler:Execution of job "runsync (trigger: interval[0:00:01], next run at: 2015-12-01 11:50:42 UTC)" skipped: maximum number of running instances reached (1)
1.Is this the correct way to execute this method?
2.What does this warning mean? Does it affect the execution of tasks inside the function in anyway?
3.how to handle this?
|
python apscheduler - skipped: maximum number of running instances reached
|
% is a special character for crontab. From man 5 crontab:
The "sixth" field (the rest of the line) specifies the command to be
run. The entire command portion of the line, up to a newline or a
"%" character, will be executed by /bin/sh or by the shell specified
in the SHELL variable of the cronfile. A "%" character in the
command, unless escaped with a backslash (\), will be changed into
newline characters, and all data after the first % will be sent to
the command as standard input.
So you need to escape the % character:
curl -w "%{time_total}\n" -o /dev/null -s http://myurl.com >> ~/log
to
curl -w "\%{time_total}\n" -o /dev/null -s http://myurl.com >> ~/log
^
|
I have a cron issue with curl:
curl -w "%{time_total}\n" -o /dev/null -s http://myurl.com >> ~/log
works great and add a line in log file with total_time.
But the same line with cron doesn't do anything.
It's not a path problem because curl http://myurl.com >> ~/log works.
|
Percent sign % not working in crontab
|
I am guessing that normally when you ssh from your local machine to the machine running crond, your private key is loaded in ssh-agent and forwarded over the connection. So when you execute the command from the command line, it finds your private key in ssh-agent and uses it to log in to the remote machine.
When crond executes the command, it does not have access to ssh-agent, so cannot use your private key.
You will have to create a new private key for root on the machine running crond, and copy the public part of it to the appropriate authorized_keys file on the remote machine that you want crond to log in to.
|
I have a bash script that does ssh to a remote machine and executes a command there, like:
ssh -nxv user@remotehost echo "hello world"
When I execute the command from a command line it works fine, but it fails when is being executed as a part of crontab (errorcode=255 - cannot establish SSH connection). Details:
...
Waiting for server public key.
Received server public key and host key.
Host 'remotehost' is known and matches the XXX host key.
...
Remote: Your host key cannot be verified: unknown or invalid host key.
Server refused our host key.
Trying XXX authentication with key '...'
Server refused our key.
...
When executing locally I'm acting as a root, crontab works as root as well.
Executing 'id' from crontab and command line gives exactly the same result:
$ id
> uid=0(root) gid=0(root) groups=0(root),...
I do ssh from some local machine to the machine running crond. I have ssh key and credentials to ssh to crond machine and any other machine that the scripts connects to.
PS. Please do not ask/complain/comment that executing anything as root is bad/wrong/etc - it is not the purpose of this question.
|
Why ssh fails from crontab but succeeds when executed from a command line?
|
asterix stands for all possible values. question marks should be used for non specific value
*("all values") - used to select all values within a field. For example, "" in the minute field means *"every minute".
? ("no specific value") - useful when you need to specify something in
one of the two fields in which the character is allowed, but not the
other. For example, if I want my trigger to fire on a particular day
of the month (say, the 10th), but don't care what day of the week that
happens to be, I would put "10" in the day-of-month field, and "?" in
the day-of-week field. See the examples below for clarification.
Copied from the tutorial
|
I've been looking at the Spring Boot example for scheduling tasks (https://spring.io/guides/gs/scheduling-tasks/) and reading through some documentation (https://javahunter.wordpress.com/2011/05/05/cronscheduler-in-spring/) and I see that * and ? are used almost interchangeably.
For example, the line
@Scheduled(cron = "0 15 10 ? * *")
and
@Scheduled(cron = "0 15 10 * * ?")
do the exact same thing. So what is the difference between * and ?
|
Difference between * and ? in Spring @Scheduled(cron=".....")
|
Something in the script is calling the tput binary. tput attempts to inspect the $TERM variable to determine the current terminal so it can produce the correct control sequences. There isn't a terminal when cron is running so you get that error from tput.
You can either manually assign a TERM value to the cron job (likely dumb or something similar to that) or (and this is likely the better solution) you can find out what is calling tput and remove that call.
|
We have a shell script which is run by CRON. The shell script in turn runs a python script which downloads files from an FTP server and then runs a java log processor on those files. The process runs just fine, except that I keep on getting CRON emails even if there is no error. At least, I think there is no error. The cron email has two lines, out of which one of the lines is
tput: No value for $TERM and no -T specified
After researching a bit, I found that it's something to do with setting the $TERM variable. I am not sure, how to do that. Any help would be appreciated. Thanks!
|
"tput: No value for $TERM and no -T specified " error logged by CRON process
|
63
You don't need to set all the fields. Set just first three and it'll take care of running every day at midnight
0 0 0 * * *
Share
Improve this answer
Follow
edited Oct 26, 2021 at 17:59
amarinediary
5,12844 gold badges2929 silver badges4747 bronze badges
answered Jun 30, 2015 at 12:26
PawanPawan
1,59711 gold badge1515 silver badges1919 bronze badges
1
1
Why the downvote on this answer? It is 100% correct.
– ttarik
Jun 30, 2015 at 12:34
Add a comment
|
|
I want to run cron job daily at midnight. For this I am using
0 0 0 1-31 * *
but it doesn't work for me.
I am using the node cron. Please suggest the valid format.
|
Node cron, run every midnight
|
Aside: This is a common problem; as such this is probably a duplicate question.
The default encoding on 2.7 is ascii.
You need to provide an encoding for your program's output.
A common encoding to use is 'utf8'.
So you'd do instead:
print title.encode('utf8')
Here's one way to check the default encoding:
import sys
sys.getdefaultencoding()
# -> 'ascii'
|
This question already has answers here:
Setting the correct encoding when piping stdout in Python
(12 answers)
Closed 10 years ago.
My program works right in the commandline, but when I run it as a cron job it crashes on the error:
UnicodeEncodeError: 'ascii' codec can't encode character
u'\xa7' in position 13: ordinal not in range(128)
It crashes on the statement
print title
Why this is happening only when the app runs as a cron job? How could this be fixed?
I tried (with no help):
print unicode(title)
Python is 2.7
|
UnicodeEncodeError only when running as a cron job [duplicate]
|
Yes that is correct.
Here is a quick chart you can use for future reference
# * * * * * command to execute
# ┬ ┬ ┬ ┬ ┬
# │ │ │ │ │
# │ │ │ │ │
# │ │ │ │ └───── day of week (0 - 6) (0 to 6 are Sunday to Saturday)
# │ │ │ └────────── month (1 - 12)
# │ │ └─────────────── day of month (1 - 31)
# │ └──────────────────── hour (0 - 23)
# └───────────────────────── min (0 - 59)
|
Closed. This question is not about programming or software development. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 5 months ago.
The community reviewed whether to reopen this question 5 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I am trying to get the correct cronjob time for 1st of January every year.
I thought about this: 0 0 1 1 *
Can anybody tell me if it is correct?
|
Cronjob for 1st of January every year [closed]
|
51
You need to add yourself to the crontab group.
usermod -a -G crontab (username)
Once you have done this, you also need to make sure that cron is running. Usually this is started with start cron however upstart does not work on WSL from what I can tell, but sudo cron does the job.
One caveat to this is that once you close all bash windows, cron will stop running even though your computer runs. However, as long as you have a bash window open and cron running, it will perform as expected.
Share
Improve this answer
Follow
edited May 4, 2017 at 21:21
answered Mar 15, 2017 at 19:49
jeffpkampjeffpkamp
2,82622 gold badges2727 silver badges5252 bronze badges
6
4
This helped, Thanks! One reminder for some people like me - Restart your bash session for this to take effect.
– Ran Sagy
Mar 24, 2017 at 14:13
3
Also, if you want cron and other background jobs to keep running after you close all bash windows, you can use this vb script at start up, and it keeps a hiden instance of bash running. gist.github.com/leonelsr/cde77574519eb1fd672bc9690e01257e
– jeffpkamp
Sep 27, 2017 at 15:37
I've been using wabash and its daemon for this, but thanks for the heads up!
– Ran Sagy
Oct 2, 2017 at 15:11
3
Using the script mentioned by jeffpkamp works great. To auto-start cron I added sudo cron to my ~/.bashrc file and myuser ALL=(ALL:ALL) NOPASSWD:/usr/sbin/cron to my /etc/sudoers file.
– 11101101b
Oct 19, 2017 at 14:42
11101101b it asks for my password while starting bash on windows. Any workaround?
– black.swordsman
May 8, 2021 at 17:54
|
Show 1 more comment
|
I am trying to schedule a bash script to run with Bash on Ubuntu on Windows in Windows 10. Every time that I to write the cron, I get the following error messages in the terminal:
crontab: installing new crontab
/var/spool/cron/: mkstemp: Permission denied
crontab: edits left in /tmp/crontab.4q0z3i/crontab
Here is what the crontab entry looks like:
# m h dom mon dow command
27 10 * * * /home/admin/test.sh > /home/admin/logs/test.log 2>&1
What exactly is going on here?
|
Crontab Not Working with Bash on Ubuntu on Windows
|
I would always go a cron job, because:
That's where sysadmins will expect it to be (this point is not to be underestimated)
crontab is bullet-proof, time-tested, extremely widely used and understood
You can freely direct/analyse error/success messages where you want
Some database tasks require/prefer mysql to be off-line (eg full backup), so you've got to use cron for those - it's a bad idea to have some tasks done with cron and some done with mysql; you'll be unsure where to look
You can chain up other events that should follow if you've got a shell script
And finally, just because you can do something, doesn't mean it's a good idea. Mysql is good at data stuff. Don't use it for "shell" stuff.
|
I have to update my MySQL database every hour, and I was wondering what the advantages/disadvantages of using a cronjob VS a MySQL event? For example, which is faster? Which is safer? Thanks!
|
Cronjob or MySQL event?
|
The reason for source ~/.bashrc not working is the contents on your ~/.bashrc (default one from Ubuntu 12.04). If you look in it you will see on lines 5 and 6 the following:
# If not running interactively, don't do anything
[ -z "$PS1" ] && return
PS1 variable is set for an interactive shell, so it's absent when run via cron, even though you are executing it as a login shell. This is confirmed by contents of the file produced by /bin/bash -l -c -x 'source ~/.bashrc; echo $EDITOR > /tmp/cronjob.test':
+ source /home/plee/.bashrc
++ '[' -z '' ']'
++ return
To make source ~/.bashrc work, comment out the line that checks for presence of the PS1 variable in ~/.bashrc:
~/.bashrc0
This will make ~/.bashrc1 execute the entire contents of ~/.bashrc2 via ~/.bashrc3
|
Here is my cron job:
plee@dragon:~$ crontab -l
* * * * * /bin/bash -l -c 'source ~/.bashrc; echo $EDITOR > /tmp/cronjob.test'
and inside ~/.bashrc file, I have export EDITOR=vim, but in the final /tmp/cronjob.test file, it's still empty?
So how can I get the environment variables (set in .bashrc file) and use it in my cron job?
plee@dragon:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 12.04 LTS
Release: 12.04
Codename: precise
plee@dragon:~$ uname -a
Linux dragon 3.2.0-26-generic-pae #41-Ubuntu SMP Thu Jun 14 16:45:14 UTC 2012 i686 i686 i386 GNU/Linux
If use this:
* * * * * /bin/bash -l -c -x 'source ~/.bashrc; echo $EDITOR > /tmp/cronjob.test' 2> /tmp/cron.debug.res
In /tmp/cron.debug.res:
...
++ return 0
+ source /home/plee/.bashrc
++ '[' -z '' ']'
++ return
+ echo
BTW, the .bashrc file is the default one came with Ubuntu 12.04, with the exception that I added one line ~/.bashrc0.
If I don't use the cron job, instead, just directly do this on the command line:
~/.bashrc1
|
Cron job does NOT get the environment variables set in .bashrc
|
36
Google has officially enabled cron in the AppEngine, for more details check:
Cron for Python:
http://code.google.com/appengine/docs/python/config/cron.html
Cron for Java:
http://code.google.com/appengine/docs/java/config/cron.html
Share
Improve this answer
Follow
edited Aug 20, 2014 at 15:34
community wiki
3 revs, 2 users 69%Benjamin Ortuzar
1
And now you can do it using a cloud function: firebase.googleblog.com/2019/04/…
– Eusthace
May 9, 2019 at 13:25
Add a comment
|
|
How can I use Cron on Google App Engine?
|
Use of Cron jobs in Google App Engine
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.