I work on an application that uses native Unix CRON tab for scheduling jobs. the description of parameters are as follows :
Minute, Hour, Da_of_Week(1-7, 1=Sun), Day_of_Month(1-31), Day_of_Year(1-365), Week (1-52), Month (1-12)
I want to run a job on Monday of the 1st week of the year at 8 pm, but I don't know how to determine when the week starts. Is 31 Dec 2017 - 06th Jan 2018 a first week or 7th Jan to 13th Jan 2018 a first week ?
You have to put a condition in your
crontab
to do that. Yourcron
will look something like this,cron
0 20 1-7 1 *
runs at 8pm everyday from 1st to 7th in the month of January.Following checks that the day is Monday before executing your script.
With this, script will run on the
7th January 2019
, which is within the first week of the year.Having cron jobs running on particular week numbers is not easy as everything depends on the definition of week numbers you are used too.
European (ISO 8601)
This ISO 8601 standard is widely used in the world: EU and most of other European countries, most of Asia, and Oceania
The ISO 8601 standard states the following:
With this definition, it is possible to have a week number 53. These occur with the first of January is on a Friday (E.g. 2016-01-01, 2010-01-01). Or, if the year before was a leap year, also a Saturday. (E.g. 2005-01-01)
American or Islamic (Not ISO 8601)
Not all countries use the ISO 8601 system. They use a more absolute approach. The American system is used in Canada, United States, New Zealand, India, Japan,... The Islamic system is generally used in the middle east. Both systems are very similar.
American:
Islamic:
With these definitions, it is possible to have partial weeks at the beginning and the end of a year. Hence the first and last week of the year could not contain all weekdays.
Note: this could be particularly cumbersome for the task you try to perform. Especially if it has to occur on the Monday of the first week. This Monday might not exist.
Importing this in the cron
Adding these systems to the cron cannot be done in a direct way. The week testing should be done by means of a conditional test of the form
For a cronjob to be run only on the Monday of the 4th week of the year at 20:00 system time (as the OP requested), the crontab would look then as:
With
weektestcmd
defined asISO 8601 week numbers:
American calendar week numbers:
Islamic calendar week numbers:
Note: Be aware that in the American and Islamic system it might be possible not to have a Monday in week 1.
Note: There are other methods of defining a week number. Nonetheless, the approach stays the same. Define a script which checks the week number and use it in the cron.