How do I add pre-hook and post-hook scripts that run before all of my cron jobs?

ⅰ亾dé卋堺 提交于 2020-01-13 22:40:33

问题


Suppose I have the following cron entry:

* * * * * /bin/date

Now suppose that I want scripts that run both before and after the cron job runs.

I could modify the cron entry to look like this:

* * * * * /bin/prehook ; /bin/date ; /bin/posthook

Or if I wanted the exit code of the prehook to determine whether or not the date command runs, I could do this:

* * * * * /bin/prehook && /bin/date ; /bin/posthook

However, I'm looking for a solution that I might be able to apply globally to all cron jobs without editing every single crontab; I see this as analogous to pre-commit and post-commit hooks that you see in many version control systems.


回答1:


I don't think there exists an easy solution using a standard cron implementation like Vixie cron unmodified.

Wrapping all the jobs in a single crontab should be achievable quite easily by setting SHELL in the crontab to a custom wrapper script, but there doesn't seem to be a way to globally configure the default shell used.

If moving away to another cron implementation is an option, then eg. bcron seems to use a global wrapper script for similar purposes. But I have no idea how alive and usable this project is.




回答2:


The system I use is that a crontab entry always consists of a single script name, such as:

3  1  *  *  *  /home/me/bin/Cron/daily

The script in /home/me/bin/Cron/daily is actually a link to a single script, runcron, which looks at what it is called (e.g. daily). It sets my environment (since cron does not set more than the very barest of minimal environments), and then runs /home/me/bin/daily. If (when) I need to debug cron, or add pre-hooks or post-hooks, I can do it globally (by modifying /home/me/bin/Cron/runcron) or locally (by making /home/me/bin/Cron/daily temporarily into a modified copy of the normal runcron script). This flexibility is very useful on those occasions when I need it, and doesn't involve any change in the actual crontab entry.

My scripts do relay arguments if they're provided. I've never found sufficient reason to use that functionality in the long term, though. I have entries for daily, weekday, weekly and monthly. (See also Where can I set environment variables that crontab will use?)



来源:https://stackoverflow.com/questions/9548595/how-do-i-add-pre-hook-and-post-hook-scripts-that-run-before-all-of-my-cron-jobs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!