ÔõÑùÔÚLinuxϵͳÖÐʹÓÃSystemdºÍCrontabʵÏÖϵͳ×ÔÆô¶¯
ÔõÑùÔÚLinuxϵͳÖÐʹÓÃSystemdºÍCrontabʵÏÖϵͳ×ÔÆô¶¯
СÐò£º
ÔÚLinuxϵͳÖУ¬ÎÒÃǾ³£ÐèÒª½«Ò»Ð©³£ÓõÄЧÀÍ»ò¾ç±¾ÉèÖÃΪϵͳ×ÔÆô¶¯£¬ÒÔ±ãϵͳÖØÆôºóÄܹ»×Ô¶¯ÔËÐС£ÔÚ±¾ÎÄÖУ¬½«ÏÈÈÝÔõÑùʹÓÃSystemdºÍCrontabÕâÁ½¸ö¹¤¾ßÀ´ÊµÏÖϵͳ×ÔÆô¶¯£¬²¢¸ø³öÏêϸµÄ´úÂëʾÀý¡£
Ò»¡¢SystemdµÄʹÓÃ
SystemdÊÇLinux²Ù×÷ϵͳÖг£ÓõÄϵͳºÍЧÀÍÖÎÀí¹¤¾ß¡£ËüÌṩÁËÀû±ãµÄÉèÖýӿڣ¬¿ÉÒÔÇáËÉÖÎÀíºÍ¿ØÖÆϵͳµÄÖÖÖÖЧÀÍ¡£
±àдһ¸öSystemdЧÀ͵¥Î»Îļþ
Ê×ÏÈ£¬ÎÒÃÇÐèÒª½¨ÉèÒ»¸öSystemdЧÀ͵¥Î»Îļþ£¬¸ÃÎļþ½ç˵ÁËÎÒÃÇÒª×ÔÆô¶¯µÄЧÀ͵ÄÏà¹ØÐÅÏ¢¡£Ð½¨Ò»¸öÒÔЧÀÍÃûÃüÃûµÄÎļþ£¬ºó׺Ϊ.service£¬ÀýÈçmy_service.service¡£ÒÔÏÂÊÇÒ»¸öʾÀýµÄServiceµ¥Î»ÎļþµÄÄÚÈÝ£º
[Unit] Description=My Service After=network.target [Service] ExecStart=/path/to/your_script.sh Type=simple Restart=always User=root [Install] WantedBy=default.target
µÇ¼ºó¸´ÖÆ µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄʾÀýÖУ¬DescriptionÓÃÓÚÐÎòЧÀ͵ÄÃû³Æ£¬AfterÖ¸¶¨ÁËЧÀÍÆô¶¯µÄÒÀÀµ¹Øϵ£¬ExecStartÖ¸¶¨ÁËЧÀÍÆô¶¯Ê±ÒªÖ´Ðеľ籾»ò³ÌÐò£¬TypeÖ¸¶¨ÁËЧÀ͵ÄÀàÐÍ£¬RestartÖ¸¶¨ÁËЧÀÍ×èÖ¹ºóÊÇ·ñ×Ô¶¯ÖØÆô£¬UserÖ¸¶¨ÁËЧÀÍÔËÐеÄÓû§¡£
ÆäÖУ¬WantedByÊÇÒ»¸öÁ´½ÓÄ¿µÄ£¬ÓÃÓÚÖ¸¶¨systemdÓ¦¸ÃÔÚÄĸö.targetÏÂ×Ô¶¯Æô¶¯Õâ¸öЧÀÍ£¬Ä¬ÈÏÇéÐÎÏÂΪdefault.target¡£
½«Ð§ÀÍÎļþ·ÅÈëϵͳµÄSystemdĿ¼ÖÐ
½«±àдºÃµÄЧÀ͵¥Î»Îļþ£¬Òƶ¯µ½ÏµÍ³µÄSystemdЧÀÍĿ¼Ï£¬Ò»Ñùƽ³£Îª/etc/systemd/system/¡£ÔÚÖÕ¶ËÖÐÖ´ÐÐÒÔÏÂÏÂÁîÍê³É²Ù×÷£º
sudo mv my_service.service /etc/systemd/system/
µÇ¼ºó¸´ÖÆ
Æô¶¯Ð§ÀͲ¢ÉèÖÃ×ÔÆô¶¯
Íê³ÉÒÔÉÏ°ì·¨ºó£¬¾Í¿ÉÒÔʹÓÃÒÔÏÂÏÂÁîÀ´Æô¶¯ºÍ×èֹЧÀÍÁË£º
sudo systemctl start my_service sudo systemctl stop my_service
µÇ¼ºó¸´ÖÆ
ΪÁËÉèÖøÃЧÀÍΪϵͳ×ÔÆô¶¯£¬Ö»ÐèÖ´ÐÐÒÔÏÂÏÂÁ
sudo systemctl enable my_service
µÇ¼ºó¸´ÖÆ
ÕâÑù£¬µ±ÏµÍ³ÖØÆôºó£¬¸ÃЧÀͽ«×Ô¶¯Æô¶¯¡£
¶þ¡¢CrontabµÄʹÓÃ
CrontabÊÇÒ»¸öÓÃÀ´ÔÚLinuxϵͳÖа´ÆÚÖ´ÐÐʹÃüµÄ¹¤¾ß¡£ÎÒÃÇ¿ÉÒÔʹÓÃCrontabÀ´ÉèÖÃϵͳÖØÆôºóÒª×Ô¶¯Ö´ÐеÄʹÃü¡£
±à¼CrontabÎļþ
ʹÓÃÒÔÏÂÏÂÁî±à¼Ä¿½ñÓû§µÄCrontabÎļþ£º
crontab -e
µÇ¼ºó¸´ÖÆ
ÔÚ±à¼Æ÷ÖÐÌí¼ÓÒÔÏÂÄÚÈÝ£º
@reboot /path/to/your_script.sh
µÇ¼ºó¸´ÖÆ
ÆäÖÐ@rebootÌåÏÖÔÚϵͳÆô¶¯ºóÖ´ÐУ¬/path/to/your_script.shÊÇÒªÖ´Ðеľ籾»ò³ÌÐòµÄ·¾¶¡£
ÉúÑIJ¢Í˳ö±à¼Æ÷
ÉúÑIJ¢Í˳ö±à¼Æ÷ºó£¬Crontab»á×Ô¶¯ÉúЧ¡£
ÑéÖ¤ÉèÖÃ
ʹÓÃÒÔÏÂÏÂÁî¿ÉÒÔÉó²éÄ¿½ñÓû§µÄCrontabÉèÖãº
crontab -l
µÇ¼ºó¸´ÖÆ
ÈôÊÇÄܹ»¿´µ½ÊʲÅÌí¼ÓµÄÄÚÈÝ£¬ÔòÌåÏÖÉèÖÃÀֳɡ£
½áÂÛ£º
ͨ¹ýʹÓÃSystemdºÍCrontab¹¤¾ß£¬ÎÒÃÇ¿ÉÒÔÀû±ãµØʵÏÖ Linux ϵͳÖØÆôºóµÄ×Ô¶¯Æô¶¯¹¦Ð§¡£Ê¹Óà Systemd ¿ÉÒÔÖÎÀíϵͳµÄÖÖÖÖЧÀÍ£¬²¢ÇÒ¿ÉÒÔͨ¹ý¼òÆÓµÄÉèÖÃÎļþÀ´ÊµÏÖ×Ô¶¯Æô¶¯¡£¶øʹÓà Crontab Ôò¿ÉÒÔʵÏÖ°´ÆÚÖ´ÐÐʹÃüµÄ¹¦Ð§¡£
´úÂëʾÀý£º
ÒÔÏÂÊÇÒ»¸öʾÀýµÄ¾ç±¾£¬Õ¹Ê¾ÁËÔõÑùʹÓÃSystemdºÍCrontabÀ´ÊµÏÖϵͳ×ÔÆô¶¯µÄ¹¦Ð§¡£
SystemdЧÀ͵¥Î»Îļþ my_service.service£º
[Unit] Description=My Service After=network.target [Service] ExecStart=/path/to/your_script.sh Type=simple Restart=always User=root [Install] WantedBy=default.target
µÇ¼ºó¸´ÖÆ µÇ¼ºó¸´ÖÆ
CrontabÉèÖÃÎļþ£º
@reboot /path/to/your_script.sh
µÇ¼ºó¸´ÖÆ
ÒÔÉϾÍÊǹØÓÚÔõÑùÔÚLinuxϵͳÖÐʹÓÃSystemdºÍCrontabÀ´ÊµÏÖϵͳ×ÔÆô¶¯µÄÒªÁìºÍÏêϸ´úÂëʾÀý¡£Ï£Íû±¾ÎÄÄܹ»¶ÔÄãÓÐËù×ÊÖú¡£
ÒÔÉϾÍÊÇÔõÑùÔÚLinuxϵͳÖÐʹÓÃSystemdºÍCrontabʵÏÖϵͳ×ÔÆô¶¯µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡