cron 调度是如何实际实现的,并确保脚本按时运行?

Jim*_*Jim 10 linux cron scheduling

我想问一下 cron 工作。好的,我们将脚本放在 crontab 中,然后 cron 守护程序执行它们。

现在,如果我理解这一点,每分钟,cron 都会检查每个用户的 crontab 并执行配置的脚本。但这实际上是如何完成的?它是否分叉子进程等?

它不能按顺序执行任务,因为时间会丢失(例如,由于等待长时间运行的脚本完成)。那么这实际上是如何实施的。

只是为了提供帮助,我不是在寻找低级代码。高级描述(可能是算法?)或在大多数发行版中如何实现对我来说就足够了。

slm*_*slm 9

我在 StackOverflow 上发现了这个问答,标题是:cron 如何在内部安排作业?.

摘自那篇文章和关于 cron维基百科文章

The algorithm used by this cron is as follows:

1. On start-up, look for a file named .crontab in the home directories of 
   all account holders.

2. For each crontab file found, determine the next time in the future that
   each command is to be run.

3. Place those commands on the Franta-Maly event list with their corresponding
   time and their "five field" time specifier.

4. Enter main loop:

   1. Examine the task entry at the head of the queue, compute how far in 
      the future it is to be run.

   2. Sleep for that period of time.

   3. 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.

   4. Determine the next time in the future to run this command and place 
      it back on the event list at that time
Run Code Online (Sandbox Code Playgroud)

这个超级用户问答题为:cron 是如何工作的?涵盖了您的一些其他问题。例如,关于 cron 如何处理同时安排的作业的问题。该线程中的一个答案指出,当 cron 守护进程处理每个任务时,它会分叉每个计划的作业,因此没有单个作业会充当具有重叠时间的作业的阻止程序。