Linux Systemd Crontabʵ¼ùÖ¸ÄÏ£ºÔõÑùÓÅ»¯ºÍµ÷½â׼ʱʹÃü
Linux Systemd Crontabʵ¼ùÖ¸ÄÏ£ºÔõÑùÓÅ»¯ºÍµ÷½â׼ʱʹÃü
СÐò£º
ÔÚLinuxϵͳÖУ¬×¼Ê±Ê¹ÃüÊÇÒ»ÏîºÜÊÇÖ÷ÒªµÄ¹¦Ð§¡£¶øÔÚSystemdϵͳÏ£¬Crontab׼ʱʹÃüÖÎÀíÆ÷ÊÇÒ»ÖÖ¿ÉÒÔÌṩ׼ȷ¡¢ÎÞаºÍ¿ÉÉèÖõÄ׼ʱʹÃüÖÎÀí¹¤¾ß¡£±¾ÎĽ«ÏÈÈÝÔõÑùͨ¹ýSystemd Crontab¾ÙÐÐ׼ʱʹÃüµÄÓÅ»¯ºÍµ÷½â£¬Í¬Ê±ÌṩÏêϸµÄ´úÂëʾÀý¹©¶ÁÕ߲ο¼¡£
I. Systemd Crontab¼ò½é
Systemd CrontabÊÇLinuxϵͳϵÄÒ»¸öcron¹¤¾ß£¬ËüÊÇÓÉSystemdϵͳÖÎÀíÆ÷ÌṩµÄÒ»ÖÖ¸üÏÖ´ú»¯µÄÌæ»»ÒªÁì¡£Ïà½ÏÓڹŰåµÄcron¹¤¾ß£¬Systemd Crontab¾ßÓиüÇ¿Ê¢µÄ¹¦Ð§ºÍ¸üÎÞаµÄÉèÖÃÑ¡Ïî¡£
II. Systemd CrontabµÄ×°ÖÃÓëÉèÖÃ
×°ÖÃSystemd Crontab
Ôڴ󲿷ÖLinux¿¯ÐаæÖУ¬Systemd CrontabÊÇĬÈÏ×°Öõġ£ÈôÊÇÄúµÄϵͳÖÐûÓÐ×°Öøù¤¾ß£¬¿ÉÒÔͨ¹ý°ü¹ÜÀíÆ÷¾ÙÐÐ×°Öã¬ÒÔUbuntuΪÀý£º
sudo apt-get update sudo apt-get install cronie
µÇ¼ºó¸´ÖÆ
ÉèÖÃSystemd Crontab
Systemd CrontabµÄÉèÖÃÎļþλÓÚ/etc/cron.dĿ¼Ï£¬Ã¿Ò»¸öʹÃüÕ¼ÓÐÒ»¸öÎļþ¡£½¨ÉèÒ»¸öеÄʹÃüÎļþ£¬ÀýÈçmytask.cron£º
sudo nano /etc/cron.d/mytask.cron
µÇ¼ºó¸´ÖÆ
ÔÚmytask.cronÖУ¬ÊäÈëÒÔÏÂÄÚÈݲ¢ÉúÑÄ£º
# m h dom mon dow user command */10 * * * * root /path/to/mytask.sh
µÇ¼ºó¸´ÖÆ
ÉÏÊöÉèÖÃÌåÏÖÿ¸ô10·ÖÖÓÖ´ÐÐÒ»´Îmytask.sh¡£ÏêϸµÄʱ¼äÉèÖÃÇë²Î¿¼Cron±í´ïʽ¡£
III. Systemd Crontab³£ÓÃÏÂÁîÓëÉèÖÃ
Éó²é׼ʱʹÃüÈÕÖ¾
sudo journalctl -u cron.service
µÇ¼ºó¸´ÖÆ
ͨ¹ý¸ÃÏÂÁî¿ÉÒÔÉó²éSystemd CrontabµÄÔËÐÐÈÕÖ¾£¬Àû±ãÅŲé׼ʱʹÃüÖ´ÐÐÒì³£µÄÎÊÌâ¡£
ÖØÆôSystemd CrontabЧÀÍ
sudo systemctl restart cron.service
µÇ¼ºó¸´ÖÆ
ÔÚÐÞ¸ÄÁËSystemd CrontabµÄÉèÖÃÖ®ºó£¬ÐèÒªÖØÆôЧÀÍʹÉèÖÃÉúЧ¡£
IV. Systemd CrontabµÄÓÅ»¯Óëµ÷½â
µ÷½âʹÃüÖ´ÐÐ˳Ðò
ÔÚSystemd CrontabÖУ¬¿ÉÒÔΪÿ¸öʹÃüÎļþÉèÖÃÓÅÏȼ¶£¬´Ó¶øµ÷½âʹÃüµÄÖ´ÐÐ˳Ðò¡£ÔÚʹÃüÎļþµÄÎļþÃûÖмÓÈëÊý×Öǰ׺£¬Êý×ÖԽС£¬ÓÅÏȼ¶Ô½¸ß¡£ÀýÈ磬ÈôÊÇÄãÏ£ÍûÓÅÏÈÖ´ÐÐmytask.cron£¬¿ÉÒÔ½«ÆäÎļþÃûÐÞ¸ÄΪ01-mytask.cron¡£
×ÊÔ´ÏÞÖÆÓëÏÞÖÆÌõ¼þ
ÔÚSystemd CrontabÖУ¬¿ÉÒÔͨ¹ýÔÚʹÃüÎļþÖÐÌí¼Ó×ÊÔ´ÏÞÖƺÍÏÞÖÆÌõ¼þÀ´ÓÅ»¯×¼Ê±Ê¹ÃüµÄÖ´ÐС£ÀýÈ磬¿ÉÒÔÉèÖÃʹÃüµÄÄÚ´æÏÞÖÆ¡¢CPUʹÓÃÏÞÖƵȡ£ÏêϸµÄÉèÖÃÇë²Î¿¼SystemdÎĵµ¡£
²¢ÐÐÖ´ÐÐʹÃü
ÈôÊÇϵͳÖÐÓжà¸ö׼ʱʹÃüÐèҪͬʱִÐУ¬²¢ÇÒ²»Ï£ÍûËüÃÇÏ໥ӰÏ죬¿ÉÒÔ½«ÕâЩʹÃü»®·Ö°²ÅÅÔÚ²î±ðµÄʹÃüÎļþÖС£Systemd Crontab»á×Ô¶¯²¢ÐÐÖ´ÐÐÕâЩʹÃü¡£
ÔöÌíʹÃüËø¶¨
ΪÁË×èֹij¸öʹÃüÖظ´Ö´Ðлò±»Í¬Ê±Ö´Ðжà´Î£¬¿ÉÒÔÔÚʹÃüÎļþÖÐÌí¼ÓËø¶¨¹¦Ð§¡£Ôھ籾ÖÐʹÓÃÎļþËø£¬Ö»Óе±ÎļþËø²»±£´æʱ²ÅÖ´ÐÐʹÃü¡£Ê¾Àý´úÂëÈçÏ£º
#!/bin/bash lockfile=/tmp/mytask.lock if ( set -o noclobber; echo "$$" > "$lockfile") 2> /dev/null; then trap 'rm -f "$lockfile"; exit $?' INT TERM EXIT # ʹÃüÖ´ÐдúÂë rm -f "$lockfile" else echo "Task is already running" exit 1 fi
µÇ¼ºó¸´ÖÆ
V. ½áÓï
ͨ¹ýSystemd Crontab£¬ÎÒÃÇ¿ÉÒÔÔ½·¢ÎÞаºÍ׼ȷµØÉèÖúÍÖÎÀí׼ʱʹÃü¡£±¾ÎĶÔSystemd CrontabµÄ×°Öá¢ÉèÖúÍÓÅ»¯¾ÙÐÐÁËÏêϸÏÈÈÝ£¬²¢ÌṩÁËÏêϸµÄ´úÂëʾÀý¹©¶ÁÕ߲ο¼¡£Ï£Íû¶ÁÕßÄܹ»Í¨¹ý±¾ÎĵÄÖ¸µ¼£¬¸üºÃµØÓ¦ÓÃSystemd CrontabÀ´¾ÙÐÐ׼ʱʹÃüµÄÖÎÀíºÍÓÅ»¯¡£
ÒÔÉϾÍÊÇLinux Systemd Crontabʵ¼ùÖ¸ÄÏ£ºÔõÑùÓÅ»¯ºÍµ÷½â׼ʱʹÃüµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡