Suppose the computer is being launched irregularly. And I want to run a certain script at boot time once in a month. But I can't setup a cron job as I don't know whether the machine will be booted at this date.

I though about this approach.

  • I create a file with last date time of script execution.
  • Every boot I do the following:

    if(<<more then a month has passed since last date time>>)
        <<run script>>
    <<run script>>

<<write current date time into the file>>

Is is possible to do it using some standard tools without the trick with file?


Just* run it at either schedule using cron and check the other part of the schedule in the script:

One way:

@reboot /path/to/my_script.sh

if has_run_this_month() {

Other way:

0 0 1 * * /path/to/my_script.sh

if has_run_since_reboot() {

* There are several issues with this way of running things:

  • Do you ever keep a machine running for more than a month? Two months? What happens in either case?
  • Do you ever leave the machine off for more than a month? You can see where this is going…
  • How do you make sure the path where you persist the state (because you have to store it somewhere persistent) doesn't get wiped out at boot because it's a RAM disk?
  • So, you add the job into cron file. At midnight every 1-st day of the month the script must be run. What is "has_run_since_reboot()"? Where to add this? – user4035 Dec 13 '15 at 18:12
  • "How do you make sure the path where you persist the state" - I wanted to save the file into /root/file.txt – user4035 Dec 13 '15 at 18:13
  • "Do you ever keep a machine running for more than a month?" - no. So, I think, I can just start the script every boot. – user4035 Dec 13 '15 at 18:14
  • You'll need to implement has_run_since_reboot. You could for example save a file to a RAM disk so that it will be wiped on boot, or you could update the modified timestamp on a file, and check whether the timestamp is after the last startup time. – l0b0 Dec 13 '15 at 18:20
  • If I write 0 0 1 * * /path/to/my_script.sh in cron will it run during the next boot if the machine was off at 0:0 1-st day of the month? – user4035 Dec 13 '15 at 18:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.