ÔõÑùÔÚLinuxϵͳÖÐʹÓÃSystemdÖÎÀíCrontabʹÃü
ÔõÑùÔÚLinuxϵͳÖÐʹÓÃSystemdÖÎÀíCrontabʹÃü
СÐò£º
ÔÚLinuxϵͳÖУ¬CrontabÊÇÒ»¸ö³£ÓõÄ׼ʱʹÃüµ÷Àí¹¤¾ß¡£ËüÔÊÐíÓû§ÔÚÖ¸¶¨µÄʱ¼äÖ´ÐÐÌض¨µÄÏÂÁî»ò¾ç±¾¡£È»¶ø£¬Ëæ×Åʱ¼äµÄÍÆÒÆ£¬ÖÎÀí´ó×ÚCrontabʹÃü±äµÃÔ½À´Ô½ÖØ´ó£¬ÎÒÃÇÐèÒªÒ»ÖÖ¸üºÃµÄ·½·¨À´ÖÎÀíÕâЩʹÃü¡£SystemdÊÇÒ»¸öÔÚÏÖ´úLinuxϵͳÖÐÖÎÀíºÍÆô¶¯ÏµÍ³Ð§À͵Ť¾ß£¬ËüÌṩÁËÒ»ÖÖ¸üÎÞаºÍ¿É¿¿µÄ·½·¨À´ÖÎÀí׼ʱʹÃü¡£±¾ÎĽ«ÏÈÈÝÔõÑùʹÓÃSystemdÀ´ÖÎÀíCrontabʹÃü£¬²¢ÌṩÏêϸµÄ´úÂëʾÀý¡£
µÚÒ»²½£º½¨ÉèCrontabʹÃüÎļþ
Ê×ÏÈ£¬ÎÒÃÇÐèÒª½¨ÉèÒ»¸öCrontabʹÃüÎļþ¡£Õâ¸öÎļþ½«°üÀ¨ÎÒÃÇÒª°´ÆÚÖ´ÐеÄÏÂÁî»ò¾ç±¾¡£ÀýÈ磬ÎÒÃÇ¿ÉÒÔ½¨ÉèÒ»¸öÃûΪmytask.shµÄ¾ç±¾Îļþ£¬²¢Ìí¼ÓһЩҪִÐеÄÏÂÁÈçÏÂËùʾ£º
#!/bin/bash echo "Hello, World!" >> /tmp/output.txt
µÇ¼ºó¸´ÖÆ
ÉúÑIJ¢¹Ø±ÕÎļþ¡£È·±£¸ÃÎļþ¾ßÓÐÖ´ÐÐȨÏÞ£¬¿ÉÒÔʹÓÃÏÂÁîchmod +x mytask.shÀ´Ìí¼ÓÖ´ÐÐȨÏÞ¡£
µÚ¶þ²½£º½¨ÉèSystemdЧÀÍÎļþ
½ÓÏÂÀ´£¬ÎÒÃÇÐèÒª½¨ÉèÒ»¸öSystemdЧÀÍÎļþ£¬ÒÔ±ãSystemd¿ÉÒÔÖÎÀí×ðÁú¿Ê±CrontabʹÃü¡£ÔÚ/etc/systemd/system/Ŀ¼Ï½¨ÉèÒ»¸öÃûΪmytask.serviceµÄÎļþ£¬²¢ÔÚÆäÖÐÌí¼ÓÒÔÏÂÄÚÈÝ£º
[Unit] Description=MyTask [Service] ExecStart=/path/to/mytask.sh [Install] WantedBy=multi-user.target
µÇ¼ºó¸´ÖÆ
È·±£½«/path/to/mytask.shÌ滻ΪÏÖʵ¾ç±¾ÎļþµÄ·¾¶¡£
µÚÈý²½£ºÆô¶¯ºÍ²âÊÔʹÃü
ÉúÑIJ¢¹Ø±Õmytask.serviceÎļþºó£¬ÎÒÃÇ¿ÉÒÔʹÓÃÒÔÏÂÏÂÁîÆô¶¯Ê¹Ãü£º
sudo systemctl start mytask.service
µÇ¼ºó¸´ÖÆ
ÎÒÃÇ¿ÉÒÔʹÓÃÒÔÏÂÏÂÁî¼ì²éʹÃüµÄ״̬£º
sudo systemctl status mytask.service
µÇ¼ºó¸´ÖÆ
ÈôÊÇÒ»ÇÐÕý³££¬ÄãÓ¦¸Ã¿´µ½Ê¹ÃüµÄ״̬Ϊ”active (running)”¡£
µÚËIJ½£ºÉèÖÃʹÃü×ÔÆô¶¯
ÈôÊÇÄãÏ£ÍûÔÚϵͳÆô¶¯Ê±×Ô¶¯Æô¶¯Ê¹Ãü£¬¿ÉÒÔʹÓÃÒÔÏÂÏÂÁʹÃüÉèÖÃΪ×ÔÆô¶¯£º
sudo systemctl enable mytask.service
µÇ¼ºó¸´ÖÆ
ÏÖÔÚ£¬Ê¹Ãü½«ÔÚϵͳÆô¶¯Ê±×Ô¶¯Æô¶¯¡£
µÚÎå²½£ºÖÎÀíʹÃü
ʹÓÃSystemdÖÎÀíCrontabʹÃüÓÐһЩÌØÁíÍâÓÅÊÆ¡£ÎÒÃÇ¿ÉÒÔʹÓÃsystemctlÏÂÁîÀ´Æô¶¯¡¢×èÖ¹¡¢ÖØÆôºÍÖØÔØʹÃü£¬¶øÎÞÐèÊÖ¶¯±à¼CrontabÎļþ¡£ÒÔÏÂÊÇһЩ³£ÓõÄÏÂÁîʾÀý£º
# Æô¶¯Ê¹Ãü sudo systemctl start mytask.service # ×èֹʹÃü sudo systemctl stop mytask.service # ÖØÆôʹÃü sudo systemctl restart mytask.service # ÖØÔØʹÃü£¨ÖØмÓÔØÉèÖÃÎļþ£© sudo systemctl reload mytask.service
µÇ¼ºó¸´ÖÆ
ͨ¹ýʹÓÃSystemd£¬ÎÒÃÇ¿ÉÒÔ¸ü¾«Á·ºÍÇåÎúµØÖÎÀíCrontabʹÃü£¬²¢ïÔÌÁËÊÖ¶¯±à¼CrontabÎļþµÄΣº¦¡£
½áÂÛ£º
ÔÚ±¾ÎÄÖУ¬ÎÒÃÇÏÈÈÝÁËÔõÑùʹÓÃSystemdÀ´ÖÎÀíCrontabʹÃü¡£Í¨¹ý½¨ÉèÒ»¸öSystemdЧÀÍÎļþ²¢Ê¹ÓÃsystemctlÏÂÁîÀ´Æô¶¯¡¢×èÖ¹¡¢ÖØÆôºÍÖØÔØʹÃü£¬ÎÒÃÇ¿ÉÒÔ¸üÀû±ãµØÖÎÀí׼ʱʹÃü¡£ÕâÖÖ·½·¨ÌṩÁ˸üÎÞаºÍ¿É¿¿µÄÖÎÀí·½·¨£¬ïÔÌÁËÊÖ¶¯±à¼CrontabÎļþµÄΣº¦¡£Ï£Íû±¾ÎĶÔÄãÔÚLinuxϵͳÖÐÖÎÀíCrontabʹÃüʱÓÐËù×ÊÖú¡£
ÒÔÉϾÍÊÇÔõÑùÔÚLinuxϵͳÖÐʹÓÃSystemdÖÎÀíCrontabʹÃüµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡