Linux Systemd CrontabÈëÃŽ̳̣º´Ó»ù´¡µ½½ø½×
Linux Systemd CrontabÈëÃŽ̳̣º´Ó»ù´¡µ½½ø½×
СÐò£º
ÔÚLinuxϵͳÖУ¬ÎÒÃǾ³£ÐèÒª°´ÆÚÖ´ÐÐijЩʹÃü£¬ÀýÈ籸·ÝÊý¾Ý¡¢ÕûÀíÔÝʱÎļþµÈ¡£ÎªÁË×Ô¶¯»¯ÕâЩʹÃüµÄÖ´ÐУ¬ÎÒÃÇ¿ÉÒÔʹÓÃCrontabÀ´½¨ÉèºÍÖÎÀí׼ʱʹÃü¡£¶øÔÚ×îеÄLinux¿¯ÐаæÖУ¬SystemdÒѾ³ÉΪÁËÖ÷Á÷µÄϵͳ³õʼ»¯ºÍÖÎÀí¹¤¾ß¡£±¾ÎĽ«ÏÈÈÝÔõÑùʹÓÃSystemdµÄCrontabÀ´ÊµÏÖ׼ʱʹÃüµÄ±àд¼°ÖÎÀí£¬ÒÔ¼°Ò»Ð©½ø½×¼¼ÇÉ¡£
Ò»¡¢CrontabµÄ»ù´¡ÖªÊ¶
CrontabµÄ¿´·¨£ºCrontabÊÇÒ»ÖÖÓÃÓÚÔÚÌØ׼ʱ¼ä¾àÀëÖ´ÐÐÏÂÁî»òÕ߾籾µÄ¹¤¾ß¡£Ëü¿ÉÒÔͨ¹ýÔÚϵͳÖеÄCrontabÎļþÖбàдʹÃüÀ´ÊµÏÖ¡£
CrontabµÄÎļþ×éÖ¯½á¹¹£ºCrontabÎļþλÓÚ/var/spool/cronĿ¼Ï£¬Ã¿¸öÓû§¶¼ÓÐ×Ô¼ºµÄCrontabÎļþ¡£ÏµÍ³ÖÎÀíÔ±µÄCrontabÎļþÔò°²ÅÅÔÚ/etc/crontabÖС£CrontabÎļþÓÉÈô¸ÉÐÐ×é³É£¬Ã¿ÐÐΪһ¸öCronʹÃü¡£
CrontabµÄʱ¼äÃûÌãºCrontabʹÃüµÄʱ¼äÃûÌÃÊÇÓÉ5¸ö×Ö¶Î×é³É£¬»®·ÖÌåÏÖ·ÖÖÓ¡¢Ð¡Ê±¡¢ÈÕÆÚ¡¢Ô·ݺÍÐÇÆÚ¡£ÕâЩ×Ö¶ÎÖ®¼äÓÿոñÍÑÀë¡£
CrontabµÄÏÂÁîÃûÌãºÔÚCrontabÎļþÖУ¬Ã¿Ò»Ðж¼´ú±íÒ»¸öʹÃü¡£Ã¿¸öʹÃüÓÉʱ¼ä½ç˵ºÍÒªÖ´ÐеÄÏÂÁî×é³É¡£
¶þ¡¢Systemd CrontabµÄʹÓÃÒªÁì
±àдCrontabÎļþ£ºÊ¹ÓÃvim»òÆäËû±à¼Æ÷·¿ªCrontabÎļþ£¬ÀýÈ磺
sudo vim /etc/crontab
µÇ¼ºó¸´ÖÆ
±àдCrontabʹÃü£ºÔÚÎļþÖÐÌí¼Ó׼ʱʹÃü¡£ÀýÈ磬ÎÒÃǽ¨ÉèÒ»¸öÌìÌìÔçÉÏ8µãÖ´Ðеı¸·ÝʹÃü£¬ÏÂÁîÈçÏ£º
0 8 * * * root /path/to/backup.sh
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÊöÏÂÁîÖУ¬Ç°ÃæµÄ”0 8 *”´ú±í¸ÃʹÃü½«ÔÚÌìÌìµÄ8µãÖ´ÐУ¬´ËºóÃæµÄ”/path/to/backup.sh”ÊDZ¸·Ý¾ç±¾µÄ·¾¶¡£
ÉúÑIJ¢Í˳öCrontabÎļþ£ºÉúÑÄCrontabÎļþºó£¬Ê¹ÓÔCtrl+X”Í˳ö±à¼Æ÷¡£
ÖØÆôSystemd CrontabЧÀÍ£ºÎªÁËʹеÄCrontabʹÃüÉúЧ£¬ÎÒÃÇÐèÒªÖØÆôSystemd CrontabЧÀÍ¡£Ê¹ÓÃÒÔÏÂÏÂÁî¾ÙÐÐÖØÆô£º
sudo systemctl restart cron.service
µÇ¼ºó¸´ÖÆ
Éó²éCrontabʹÃü£ºÒªÉó²éÒѾ½¨ÉèµÄCrontabʹÃü£¬¿ÉÒÔʹÓÃÒÔÏÂÏÂÁ
sudo crontab -l
µÇ¼ºó¸´ÖÆ
Èý¡¢Ê¹ÓÃSystemd CrontabµÄ½ø½×¼¼ÇÉ
ʹÓÃCrontabµÄÇéÐαäÁ¿£ºÔÚCrontabʹÃüÖУ¬ÎÒÃÇ¿ÉÒÔʹÓÃÉèÖÃÇéÐαäÁ¿¡£ÀýÈ磬ÔÚʹÃüÖÐʹÓÃÒÔÏÂÏÂÁîÀ´ÉèÖÃPATH±äÁ¿£º
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
µÇ¼ºó¸´ÖÆ
ʹÃüµÄÖض¨Ïò£ºÔÚCrontabʹÃüÖУ¬ÎÒÃÇ¿ÉÒÔÖض¨Ïò±ê×¼Êä³öºÍ¹ýʧÊä³ö£¬ÒÔÀû±ãºóÐøµÄÈÕÖ¾¼Í¼ºÍµ÷ÊÔ¡£ÀýÈ磬½«Ê¹ÃüµÄÊä³öÐÅÏ¢ÉúÑĵ½ÎļþÖУº
0 * * * * /path/to/script.sh > /path/to/logfile.log 2>&1
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÊöÏÂÁîÖУ¬”>”ÌåÏÖ½«±ê×¼Êä³öÖض¨Ïòµ½Ö¸¶¨Îļþ£¬”2>&1″ÌåÏÖ½«±ê×¼¹ýʧÊä³öÖض¨Ïòµ½Óë±ê×¼Êä³öÏàͬµÄλÖá£
½ç˵ʹÃüÖ´ÐеÄÇéÐΣºÓÐЩCrontabʹÃü¿ÉÄÜÐèÒªÔÚÌض¨µÄÔËÐÐÇéÐÎÖÐÖ´ÐС£ÎÒÃÇ¿ÉÒÔʹÓÃSystemdµÄEnvironmentÖ¸ÁîÀ´ÉèÖÃʹÃüÖ´ÐеÄÇéÐΡ£ÀýÈ磬ÔÚCrontabʹÃüÖÐʹÓÃÒÔÏ´úÂëÀ´ÉèÖÃÇéÐαäÁ¿£º
Environment="ENV_VAR=value"
µÇ¼ºó¸´ÖÆ
¿ØÖÆʹÃüµÄÖ´ÐдÎÊý£ºÓÐʱ¼ä£¬ÎÒÃÇÏ£ÍûʹÃüÄܹ»ÔÚÖ¸¶¨µÄʱ¼ä¶ÎÄÚ¶à´ÎÖ´ÐС£Systemd CrontabÌṩÁËOnCalendarÑ¡ÏîÀ´¿ØÖÆʹÃüµÄÖ´ÐдÎÊý¡£ÀýÈ磬ÒÔÏÂÏÂÁÔÚÿ¸öÔµĵÚÒ»ÌìºÍµÚ15ÌìµÄÏÂÕ½Êé2µãÖÁÏÂÕ½Êé5µãÖ®¼äÿ¸ô30·ÖÖÓÖ´ÐÐÒ»´Î£º
OnCalendar=*-01,15:14-17/30
µÇ¼ºó¸´ÖÆ
×ܽ᣺
ͨ¹ý±¾ÎĵÄÏÈÈÝ£¬ÎÒÃÇ¿ÉÒÔÏàʶµ½ÔõÑùʹÓÃSystemdµÄCrontabÀ´ÊµÏÖ׼ʱʹÃüµÄ±àдºÍÖÎÀí¡£ÎÒÃDz»µ«Ñ§»áÁË»ù´¡µÄCrontabÓ÷¨£¬»¹Ñ§»áÁËһЩ½ø½×µÄ¼¼ÇÉ£¬ÈçÇéÐαäÁ¿µÄÉèÖá¢Öض¨ÏòµÄÓ¦Óõȡ£ÕÆÎÕÕâЩ¼¼ÇÉ£¬¿ÉÒÔÔ½·¢ÎÞаºÍ¸ßЧµØÖÎÀí׼ʱʹÃü¡£Ï£Íû±¾ÎĶԸ÷ÈËÓÐËù×ÊÖú£¬Äܹ»ÔÚÏÖʵÊÂÇéÖгä·ÖÑéÕ¹Systemd CrontabµÄ×÷Óá£
ÒÔÉϾÍÊÇLinux Systemd CrontabÈëÃŽ̳̣º´Ó»ù´¡µ½½ø½×µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡