ÔõÑùʹÓÃSystemdºÍCrontabÔÚLinuxϵͳÖÐʵÏÖʹÃüÒÀÀµ¹Øϵ
ÔõÑùʹÓÃSystemdºÍCrontabÔÚLinuxϵͳÖÐʵÏÖʹÃüÒÀÀµ¹Øϵ
СÐò£º
ÔÚLinuxϵͳÖУ¬Ê¹Ãüµ÷ÀíÊǺÜÊÇÖ÷ÒªµÄÒ»»·£¬ËüÄܹ»È·±£¸÷¸öʹÃüƾ֤Ԥ¶¨µÄʱ¼äÎÂ˳ÐòÖ´ÐС£SystemdºÍCrontabÊÇÁ½ÖÖ³£ÓõÄʹÃüµ÷Àí¹¤¾ß£¬ËüÃÇ»®·ÖÊÊÓÃÓÚ²î±ðµÄ³¡¾°¡£±¾ÎĽ«ÏÈÈÝÔõÑùʹÓÃSystemdºÍCrontabÀ´ÊµÏÖʹÃüµÄÒÀÀµ¹Øϵ£¬²¢ÌṩÏêϸµÄ´úÂëʾÀý¡£
Ò»¡¢SystemdµÄʹÃüÒÀÀµ¹Øϵ
SystemdÊÇLinuxÖÐÒ»¸öÖ÷ÒªµÄϵͳºÍЧÀÍÖÎÀíÆ÷£¬Ëüͨ¹ýUnitÎļþÀ´½ç˵ºÍÖÎÀíϵͳ×ÊÔ´¡£ÎÒÃÇ¿ÉÒÔʹÓÃUnitÎļþÀ´½ç˵ʹÃüµÄÒÀÀµ¹Øϵ£¬Ê¹µÃʹÃüÄܹ»Æ¾Ö¤Ö¸¶¨µÄ˳ÐòºÍÌõ¼þÖ´ÐС£
°ì·¨ÈçÏ£º
½¨ÉèÒ»¸öUnitÎļþ£¬²¢Ê¹ÓÃ[Unit]ºÍ[Service]×Ö¶ÎÀ´½ç˵ʹÃüµÄÒÀÀµ¹Øϵ¡£
ÀýÈ磬ÎÒÃǽ¨ÉèÒ»¸öÃûΪmytask.serviceµÄUnitÎļþ£¬ÆäÖаüÀ¨ÒÔÏÂÄÚÈÝ£º
[Unit]
Description=My Task
After=network.target
[Service]
Type=simple
ExecStart=/path/to/mytask.sh
[Unit]×Ö¶ÎÓÃÓÚÐÎòʹÃüµÄ»ù±¾ÐÅÏ¢£¬[Service]×Ö¶ÎÓÃÓÚ½ç˵ʹÃüµÄÏêϸִÐз½·¨¡£
ÔÚÉÏÊöʾÀýÖУ¬ÎÒÃǽç˵ÁËÒ»¸öÃûΪmytask.serviceµÄʹÃü£¬ËüÒÀÀµÓÚnetwork.targetЧÀÍ¡£
½¨ÉèÒ»¸öShell¾ç±¾£¬ÓÃÓÚÖ´ÐÐÏêϸµÄʹÃü¡£
ÀýÈ磬ÎÒÃǽ¨ÉèÒ»¸öÃûΪmytask.shµÄShell¾ç±¾£¬ÆäÖаüÀ¨ÒÔÏÂÄÚÈÝ£º
!/bin/bash
echo “Hello, World!”
ÔÚÉÏÊöʾÀýÖУ¬ÎÒÃǼòÆÓµØÊä³öÁËÒ»Ìõ”Hello, World!”µÄÐÅÏ¢¡£
½«UnitÎļþºÍShell¾ç±¾ÉúÑĵ½Ö¸¶¨µÄĿ¼ÖС£
ÀýÈ磬ÎÒÃǽ«mytask.serviceÉúÑĵ½/etc/systemd/system/Ŀ¼Ï£¬½«mytask.shÉúÑĵ½/path/to/Ŀ¼Ï¡£
ʹÓÃsystemctlÏÂÁîÆô¶¯ºÍÖÎÀíʹÃü¡£
Ö´ÐÐÒÔÏÂÏÂÁîÒÔÆô¶¯Ê¹Ãü£º
sudo systemctl start mytask.service
Ö´ÐÐÒÔÏÂÏÂÁîÒÔ×èֹʹÃü£º
sudo systemctl stop mytask.service
Ö´ÐÐÒÔÏÂÏÂÁîÒÔÉó²éʹÃüµÄ״̬£º
sudo systemctl status mytask.service
¶þ¡¢CrontabµÄʹÃüÒÀÀµ¹Øϵ
CrontabÊÇÒ»ÖÖÓÃÓÚÉèÖð´ÆÚÖ´ÐÐʹÃüµÄÏÂÁÎÒÃÇ¿ÉÒÔʹÓÃËüÀ´ÊµÏÖʹÃüµÄÒÀÀµ¹Øϵ¡£
°ì·¨ÈçÏ£º
Ö´ÐÐcrontab -eÏÂÁ±à¼Ä¿½ñÓû§µÄCrontabÎļþ¡£
±à¼CrontabÎļþ£¬²¢ÔÚÆäÖнç˵ʹÃüµÄÒÀÀµ¹Øϵ¡£
ÀýÈ磬ÎÒÃÇ¿ÉÒÔÔÚCrontabÎļþÖÐÌí¼ÓÒÔÏÂÄÚÈÝ£º
m h dom mon dow command
0 0 * /path/to/task1.sh
10 0 * /path/to/task2.sh
ÔÚÉÏÊöʾÀýÖУ¬ÎÒÃǽç˵ÁËÁ½¸öʹÃü£ºtask1.shºÍtask2.sh¡£task2.shÒÀÀµÓÚtask1.sh£¬¼´task2.sh±ØÐèÔÚtask1.shÖ´ÐÐÍê³Éºó²Å»ªÖ´ÐС£
½¨ÉèShell¾ç±¾£¬ÓÃÓÚÖ´ÐÐÏêϸµÄʹÃü¡£
ÀýÈ磬ÎÒÃǽ¨ÉèÒ»¸öÃûΪtask1.shµÄShell¾ç±¾£¬ÆäÖаüÀ¨ÒÔÏÂÄÚÈÝ£º
!/bin/bash
echo “Task 1”
½¨ÉèÒ»¸öÃûΪtask2.shµÄShell¾ç±¾£¬ÆäÖаüÀ¨ÒÔÏÂÄÚÈÝ£º
!/bin/bash
echo “Task 2”
ÔÚÉÏÊöʾÀýÖУ¬task1.shÖ»Êä³öÁËÒ»ÌõÐÅÏ¢”Task 1″£¬task2.shÖ»Êä³öÁËÒ»ÌõÐÅÏ¢”Task 2″¡£
½«Shell¾ç±¾ÉúÑĵ½Ö¸¶¨µÄĿ¼ÖС£
ÀýÈ磬ÎÒÃǽ«task1.shÉúÑĵ½/path/to/Ŀ¼Ï£¬½«task2.shÉúÑĵ½/path/to/Ŀ¼Ï¡£
Crontab½«Æ¾Ö¤ÎÒÃǵĽç˵£¬Æ¾Ö¤Ö¸¶¨µÄʱ¼äÎÂ˳ÐòÖ´ÐÐʹÃü¡£
ͨ¹ýÒÔÉÏ°ì·¨£¬ÎÒÃÇ¿ÉÒÔÔÚLinuxϵͳÖÐʹÓÃSystemdºÍCrontabÀ´ÊµÏÖʹÃüµÄÒÀÀµ¹Øϵ¡£ÔÚÏÖʵʹÓÃÀú³ÌÖУ¬ÎÒÃÇ¿ÉÒÔƾ֤ÏÖʵÐèÇó¾ÙÐÐÎÞаµÄµ÷½âºÍÉèÖã¬ÒÔÈ·±£Ê¹Ãüƾ֤ԤÆÚµÄ˳ÐòºÍÌõ¼þÖ´ÐС£
½áÂÛ£º
SystemdºÍCrontabÊÇLinuxÖг£ÓõÄʹÃüµ÷Àí¹¤¾ß£¬¿ÉÒÔͨ¹ý½ç˵ʹÃüµÄÒÀÀµ¹Øϵ£¬ÊµÏÖʹÃüµÄÓÐÐòÖ´ÐС£±¾ÎÄÏÈÈÝÁËʹÓÃSystemdºÍCrontabʵÏÖʹÃüÒÀÀµ¹ØϵµÄÏêϸ°ì·¨£¬²¢ÌṩÁËÏìÓ¦µÄ´úÂëʾÀý¡£Ï£Íû±¾ÎÄÄܹ»¶Ô¶ÁÕßÔÚLinuxϵͳÖÐʵÏÖʹÃüÒÀÀµ¹ØϵÓÐËù×ÊÖú¡£
ÒÔÉϾÍÊÇÔõÑùʹÓÃSystemdºÍCrontabÔÚLinuxϵͳÖÐʵÏÖʹÃüÒÀÀµ¹ØϵµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡