1

I am running the following cron job

* * * * * date "+\%Y\%m\%dT\%H\%M\%S" > /path/to/log 2>&1

but it's running around a second too late, as it writes e.g.

20210817T210001

How can I ensure the cron job will run at the full minute?

2
  • 1
    It should be obvious -- with only a modicum of thought -- that it takes time for cron to "wake up", scan all crontabs, determining if an entry needs to be run. That's the harsh truth.
    – RonJohn
    Aug 19, 2021 at 21:31
  • If you require this kind of timing precision — which may also indicate a wrong choice of software for a particular purpose —, just use systemd timers instead of a completely outdated cron setup. With systemd timers you get the configuration knobs needed to strike a balance between timing precision and dispatching overhead. AccuracySec (which can have values in μs if needed) is the keyword to search for in the documentation. Also, if this is all about logging a nice round timestamp, just round the timestamp then. 😉 Aug 21, 2021 at 3:26

1 Answer 1

13

This is also covered over at Server Fault.

I personally favor this quote: "What cron can guarantee is that your job will start no sooner than the specified time." In other words, cron isn't really designed to be surgically precise to the second. Most of my own cron jobs will also start at 01 or even 02 seconds after the full minute.

In order for cron jobs to start, cron will scan what jobs need to run at any given time. It's not an error if a job scheduled to start at 12:00:00 will actually start at 12:00:01, since the amount of time for cron to initialize can vary, depending on a number of factors.

If you need something to trigger "almost" (thanks Kevin) at the exact second, you should look for another solution than cron - for instance systemd timers (thanks Andrej), a Python script or even a C program that monitors the time for you.

EDIT: Alternately (as suggested by Nonny Moose), you can schedule a script to run one minute early, and then monitor the time so it runs as precise as possible when you want it to run.

4
  • 3
    And then you can use crontab to run that script at reboot
    – Irsu85
    Aug 19, 2021 at 8:48
  • Yes, indeed! :-) Aug 19, 2021 at 8:48
  • 2
    You could even have cron start your program, say, a minute early, and then constantly monitor the time until it should run. Aug 19, 2021 at 22:08
  • 3
    Pedantically: You can't have something "trigger at the exact second." You are running under a preemptively-multitasking operating system. The kernel will schedule your process to have the CPU when the kernel feels like it, not at an exact second. If you don't like that, then you would have to use sched(7) to ask for real-time scheduling guarantees, which are still not perfect as the kernel has nonzero scheduling overhead.
    – Kevin
    Aug 19, 2021 at 22:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .