Cron a script on every alternate Saturday - python-3.x

I want to schedule some scripts in every alternate Saturday.
I have tried few things like using days of the month but they don't seems to be the best ways to get the alternate days like
10 22 1-7,15-21,29-31 * 6
There should be some better solution to cron the things on alternate Saturdays.

If you want to have special conditions, you generally need to implement the conditions yourself with a test. Below you see the general structure:
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7)
# | | | | |
# * * * * * command to be executed
10 22 * * 6 testcmd && command
The command testcmd generally returns exit code 0 if the test is successful or 1 if it fails. If testcmd is successful, it executes command. A few examples that use similar tricks are in the following posts:
Linux crontab for nth Satuday of the month
Is it possible to execute cronjob in every 50 hours?
Cron expression to run every N minutes
how to set cronjob for 2 days?
The easiest way to obtain what you are after is to select the Saturday to be falling on an odd or even week. The test command testcmd would then look like any of the following:
(( $(date "+\%d") \% 14 < 7 )) : group your month in groups of 14 days and select only the first seven of those days. This has issues that two consecutive weeks can be valid. Example, if the 30th of January is a Saturday, then both this Saturday and the next (6th of February) will be valid.
(( $(date "+\%V") \% 2 == 0 )) : group your year in groups of two weeks and select only the first of that week. This has the issue that years with 53 weeks can create two consecutive valid Saturdays on the end of December and the beginning of January. This is not frequent, but it can happen.
The most robust solution is that presented in * how to set cronjob for 2 days? where we change the problem to every 14 days. Based on my answer to that question, you can adapt it to form a little executable that would create you the perfect testcmd:
Replace in the above testcmd with /path/to/testcmd 14 20210731 where the latter is a script that reads;
#!/usr/bin/env bash
# get start time in seconds
start=$(date -d "${2:-#0}" '+%s')
# get current time in seconds
now=$(date '+%s')
# get the amount of days (86400 seconds per day)
days=$(( (now-start) /86400 ))
# set the modulo
modulo=$1
# do the test
(( days >= 0 )) && (( days % modulo == 0))

Related

CRON with AND relationship between mday and wday

I have seen this question which indicates that the relationship between the wday and mday fields of a CRON schedule is an OR relationship. Say for example I want to schedule something for every Friday the 13th.
Rather than the expected result, the CRON
0 0 13 * 5
will give me all Fridays of every month, as well as every 13th of every month.
Is there any way to avoid this behavior and specify an AND relationship? (There seems to be mention of older versions using an AND relationship, however I would prefer to use a single tool with the ability to do both)
I guess, instead of specifying the wday (Friday=5), you'll just have to specify the months where the 13th is a Friday; so, for 2019:
0 0 13 9,12 * : do stuff, but avoid black cats
Or, eternally more elegant, create a small script:
$> cat /home/me/bin/test_friday_13
#!/bin/bash
if [ "$(date +'%A %d')" != "Friday 13" ]
then
exit 1
else
: do stuff, but avoid black cats
exit 0
fi
and make the crontab entry:
0 0 13 * * /home/me/bin/test_friday_13
The script approach has the added benefit that you can run it from the command line. (Note: do not forget to alter the weekday name in the script to reflect your environment.)
The cron-entry you are interested in is:
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7)
# | | | | |
# * * * * * command to be executed
0 0 13 * * [ $(date "+\%u") = "5" ] && command
This will execute the cronjob every 13th of the month. It will compute the day of the week, and test it if it is a Friday (5). If so, it will execute command.
Extended explanation:
If you want to have special conditions, you generally need to implement the conditions yourself with a test. Below you see the general structure:
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7)
# | | | | |
# * * * * * command to be executed
0 0 13 * * /path/to/testcmd && command
The command testcmd generally returns exit code 0 if the test is successful or 1 if it fails. If testcmd is successful, it executes command. A few examples that use similar tricks are in the following posts:
Linux crontab for nth Satuday of the month
Is it possible to execute cronjob in every 50 hours?
Cron expression to run every N minutes
how to set cronjob for 2 days?
The test you want to perform is written in /bin/sh as:
[ $(date "+%u") = 5 ]
Which makes use of the test command (see man test). This is POSIX compliant and will work with any shell that your cron might run in (sh,bash,dash,ksh,zsh). The command date "+%u" returns the weekday from 1 to 7 (Sunday is 7). See man date for more info.
So your cronjob would look like:
0 0 13 * * [ $(date "+\%u") = 5 ] && command
Note that we have to escape the <percent>-character.
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.
source: man 5 crontab
Unfortunately, CRON doesn't work the way you want
You can see all available options on below url
https://www.freeformatter.com/cron-expression-generator-quartz.html
So what you can do is the execute the cron on every 13th of the month but don't let the command run when its Friday
0 0 0 13 * ? * mybatchjob.sh
mybatchjob.sh
if [ `date +'%A'` = "Friday" ]; then
echo "Yep its Friday";
else
echo "Not Friday";
fi
This will make sure that the intended program only runs on Friday and the 13th

Linux crontab for nth Satuday of the month

I like to run back up for all weekdays except Saturday.
My crontab entry
30 16 * * 1,2,3,4,5 ./backup.sh
This entry working fine.
Also, I like to take back up on 1st, 3rd Saturday.
If any 5th Sutarday available in a month then the back up should run. What will be the entry for crontab? I am guessing
30 16 1-7, 15-21, 29-31 * 6 ./backup.sh
Am I right?
Am I right?
No you are not correct. The crontab manual states:
Note: The day of a command's execution can be specified in the following two fields day of month, and day of week. If both fields are restricted (i.e., do not contain the "*" character), the command will be run when either field matches the current time. For example,
30 4 1,15 * 5 would cause a command to be run at 4:30 am on the 1st and 15th of each month, plus every Friday.
So how can we do it?
If you want to determine which Saturday of the month it is, i.e. whether it is the 1st, 2nd or 3rd Saturday of the month, all you have to do is look at the weekday of the Saturday and do the following integer computation:
D=$(date "+%d")
echo $(( (D-1)/7 + 1 ))
This value will return the corresponding number. This does not only work for Saturdays but for any Weekday.
Since the OP wants the cron to work on the 1st, 3rd and potentially the 5th Saturday, it actually states that the cron runs on every odd-numbered Saturday:
D=$(date "+%d")
echo $(( ((D-1)/7 + 1) % 2 ))
Using this as an additional test, allows us to write the cron as:
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7)
# | | | | |
# * * * * * command to be executed
30 16 * * 6 (( (($(date "+\%d") - 1)/7 + 1) % 2 == 1 )) && command

Is it possible to execute cronjob in every 50 hours?

I've been looking for a cron schedule that executes a script for every 50 hours. Running a job for each 2 days is simple with cron. We can represent like
0 0 */2 * * command
But what about every 50 hours?
If you want to run a cron every n hours, where n does not divide 24, you cannot do this cleanly with cron but it is possible. To do this you need to put a test in the cron where the test checks the time. This is best done when looking at the UNIX timestamp, the total seconds since 1970-01-01 00:00:00 UTC. Let's say we want to start from the moment McFly arrived in Riverdale:
% date -d '2015-10-21 07:28:00' +%s
1445412480
For a cronjob to run every 50th hour after `2015-10-21 07:28:00', the crontab would look like this:
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7)
# | | | | |
# * * * * * command to be executed
28 * * * * hourtestcmd "2015-10-21 07:28:00" 50 && command
with hourtestcmd defined as
#!/usr/bin/env bash
starttime=$(date -d "$1" "+%s")
# return UTC time
now=$(date "+%s")
# get the amount of hours
hours=$(( (now - starttime) / 3600 ))
# get the amount of remaining minutes
minutes=$(( (now - starttime - hours*3600) / 60 ))
# set the modulo
modulo=$2
# do the test
(( now >= starttime )) && (( hours % modulo == 0 )) && (( minutes == 0 ))
Remark: UNIX time is given in UTC. If your cron runs in a different time-zone which is influenced by daylight saving time, it could lead to programs being executed with an offset or when daylight saving time becomes active, a delta of 51hours or 49hours.
Remark: UNIX time is not influenced by leap seconds
Remark: cron has no sub-second accuracy
Remark: Note how I put the minutes identical to the one in the start time. This to make sure the cron only runs every hour.

Cron expression to run every day starting from a date

I need a cron expression which will fire every day at 12 pm starting from jan 25 2016. This is what I came up with:
0 0 12 25/1 * ? *
but after jan 31, the next firing time is feb 25.
Is there a cron expression expression for doing this? If not what can I use?
Assuming that after January 25th you want to run this process forever after (i.e. 2032, when probably the server will be already substituted), I would do it with three expressions:
0 0 12 25-31 1 * 2016 command # Will run the last days of Jan 2016 after the 25th
0 0 12 * 2-12 * 2016 command # Will run the rest of the months of 2016
0 0 12 * * * 2017-2032 command # will run for every day of years 2017 and after.
I hope this helps.
There are multiple ways to accomplish this task, One could be running a script with cron job and testing conditions and if true run actually required scripts otherwise skip.
Here is an example,
20 0 * * * home/hacks/myscript.sh
and in myscript.sh put your code to test conditions and run actual command/script
Here is an example for such a script,
#!/bin/bash
if( ( $(date) <= "31-01-2016" ) || ( $(date) >= "25-02-2017" ) ){
// execute your command/script
}else {
// do Nothing
}
You can write a date expression which only matches dates after a particular point in time; or you can create a wrapper for your script which aborts if the current date is before the time when the main script should run
#!/bin/bash
# This is GNU date, adapt as required for *BSD and other variants
[[ $(date +%s -d 2018-02-25\ 00:00:00) > $(date +%s) ]] && exit
exec /path/to/your/real/script "$#"
... or you can schedule the addition of this cron job with at.
at -t 201802242300 <<\:
schedule='0 0 12 25/1 * ? *' # update to add your command, obviously
crontab=$(crontab -l)
case $crontab in
*"$schedule"*) ;; # already there, do nothing
*) printf "%s\n" "$crontab" "$schedule" | crontab - ;;
esac
:
(Untested, but you get the idea. I just copy/pasted your time expression, I guess it's not really valid for crontab. I assume Quartz has a way to do something similar.)
The time specification to at is weird, I managed to get this to work on a Mac, but it might be different on Linux. Notice I set it to run at 23:00 on the previous night, i.e. an hour before the planned first execution.
This is a brief copy from my answer here.
The easiest way is to use an extra script which does the test. Your cron would look like :
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7)
# | | | | |
# * * * * * command to be executed
0 12 * * * daytestcmd 1 20160125 && command1
0 12 * * * daytestcmd 2 20160125 && command2
Here, command1 will execute every day from 2016-01-25 onwards. command2 will execute every second day from 2016-01-25 onwards.
with daytestcmd defined as
#!/usr/bin/env bash
# get start time in seconds
start=$(date -d "${2:-#0}" '+%s')
# get current time in seconds
now=$(date '+%s')
# get the amount of days (86400 seconds per day)
days=$(( (now-start) /86400 ))
# set the modulo
modulo=$1
# do the test
(( days >= 0 )) && (( days % modulo == 0))

Crontab job executed every day instead every month

Three days ago I installed the following crontab job with crontab -e:
# execute weekly
0 2 2-31 * 7 sh /home/user/folder/myscript.sh week > /home/user/.crontablog/crontab.log
It's supposed to be executed every sunday night at 2am except the 1st of the month. However it's executed every night at 2am. What's my mistake? I tried 0 instead of 7 for Sunday with the same result :/
Thank you.
Since the format of crontab is like this:
+---------------- minute (0 - 59)
| +------------- hour (0 - 23)
| | +---------- day of month (1 - 31)
| | | +------- month (1 - 12)
| | | | +---- day of week (0 - 6) (Sunday=0 or 7)
| | | | |
* * * * * command to be executed
To execute it every week on Sunday irrespective of the month you need to write it like this:
0 2 * * 7 sh /home/user/folder/myscript.sh week > /home/user/.crontablog/crontab.log
first you can analyze the content of /var/log/cron, grepping for your script to see what is going on.
I suggest you use the following syntax
0 2 * * sun /home/user/folder/myscript.sh week
having given the +x permission on the script file.
Cheers
Now that you respecified your question in the comments you need to do TWO things:
as I said above, use 0 2 * * 7 to run at 2:00am every Sunday; 7 and 0 are equivalent
inside your shell script use an additional test to quietly exit on the first of the month.
That test could be as simple as
test $(date +%d) == "01" && exit
but you could of course also make it a proper if ... with more echo and verbosity.
If you want to run the script every sunday night at 2am, but only if it's not the first day in the month, then you have to use this syntax:
0 2 * * 0 /usr/bin/test $(/bin/date +\%e) -ne 1 && your_command
The test utilliy finally check if it's the first day in month and your_command is only exected if it's not.

Resources