ÔõÑùͨ¹ýSystemdºÍCrontabÔÚLinuxϵͳÖÐ×Ô¶¯»¯Ð§ÀÍÆ÷¼à¿Ø
ÔõÑùͨ¹ýSystemdºÍCrontabÔÚLinuxϵͳÖÐ×Ô¶¯»¯Ð§ÀÍÆ÷¼à¿Ø
¸ÅÊö
ÔÚЧÀÍÆ÷ÖÎÀíÖУ¬¼à¿ØÊÇÒ»¸öºÜÊÇÖ÷ÒªµÄ»·½Ú¡£Í¨¹ý¼à¿ØЧÀÍÆ÷µÄ״̬ºÍÐÔÄÜ£¬¿ÉÒÔʵʱ·¢Ã÷ÎÊÌâ²¢½ÓÄÉÏìÓ¦µÄ²½·¥¾ÙÐÐÓÅ»¯ºÍÐÞ¸´¡£±¾ÎĽ«ÏÈÈÝÔõÑùʹÓÃSystemdºÍCrontabÁ½¸ö¹¤¾ßÀ´×Ô¶¯»¯Ð§ÀÍÆ÷µÄ¼à¿Ø£¬²¢ÌṩÏêϸµÄ´úÂëʾÀý¡£
Systemd
SystemdÊÇÒ»¸öLinuxϵͳµÄ³õʼ»¯ÏµÍ³ºÍЧÀÍÖÎÀíÆ÷¡£Í¨¹ýSystemd£¬ÎÒÃÇ¿ÉÒÔ½¨ÉèºÍÖÎÀí×Ô½ç˵µÄЧÀÍ£¬²¢Ö¸¶¨ËüÃǵÄÆô¶¯¡¢×èÖ¹ºÍÖØÆôÌõ¼þ¡£ÔÚЧÀÍÆ÷¼à¿ØÖУ¬ÎÒÃÇ¿ÉÒÔʹÓÃSystemdÀ´×¼Ê±ÔËÐмà¿Ø¾ç±¾¡£
ÏÂÃæÊÇÒ»¸öʹÓÃSystemdÀ´×¼Ê±ÔËÐмà¿Ø¾ç±¾µÄʾÀý£º
½¨ÉèÒ»¸öеÄSystemdЧÀÍÎļþ£¬ÀýÈçmonitor.service£º
[Unit] Description=Server Monitoring Service [Service] Type=oneshot ExecStart=/path/to/monitor.sh [Timer] OnCalendar=*:0/5 [Install] WantedBy=multi-user.target
µÇ¼ºó¸´ÖÆ
ÉÏÊöʾÀýÖУ¬ÎÒÃÇÖ¸¶¨ÁËÒ»¸öÃûΪmonitor.shµÄ¼à¿Ø¾ç±¾£¬ÒÔ¼°Ò»¸öÿ¸ô5·ÖÖÓÔËÐÐÒ»´ÎµÄ׼ʱÆ÷¡£½«¾ç±¾µÄ·¾¶Ì滻ΪÏÖʵµÄ¼à¿Ø¾ç±¾Â·¾¶£¬²¢½«Ð§ÀÍÎļþÉúÑĵ½ /etc/systemd/system Ŀ¼Ï¡£
ÆôÓò¢Æô¶¯¸ÃЧÀÍ£º
sudo systemctl enable monitor.service sudo systemctl start monitor.service
µÇ¼ºó¸´ÖÆ
Ö´ÐÐÉÏÊöÏÂÁîºó£¬¸ÃЧÀͽ«»áÔÚÿ¸ô5·ÖÖÓ×Ô¶¯ÔËÐÐÒ»´Î¼à¿Ø¾ç±¾¡£
Crontab
CrontabÊÇÒ»¸öÓÃÓÚÔÚUnixºÍUnix-likeϵͳÖÐÔËÐÐʹÃüµÄ¹¤¾ß¡£Í¨¹ýCrontab£¬ÎÒÃÇ¿ÉÒÔÔÚÖ¸¶¨µÄʱ¼äºÍÈÕÆÚÔËÐÐÏÂÁî»ò¾ç±¾¡£ÔÚЧÀÍÆ÷¼à¿ØÖУ¬ÎÒÃÇ¿ÉÒÔʹÓÃCrontabÀ´×¼Ê±ÔËÐмà¿Ø¾ç±¾¡£
ÏÂÃæÊÇÒ»¸öʹÓÃCrontabÀ´×¼Ê±ÔËÐмà¿Ø¾ç±¾µÄʾÀý£º
ʹÓÃcrontabÏÂÁî±à¼Ä¿½ñÓû§µÄcrontabÎļþ£º
crontab -e
µÇ¼ºó¸´ÖÆ
ÔÚÎļþÖÐÌí¼ÓÒÔÏÂÄÚÈÝ£º
*/5 * * * * /path/to/monitor.sh
µÇ¼ºó¸´ÖÆ
ÉÏÊöʾÀýÖУ¬ÎÒÃÇÖ¸¶¨ÁËÒ»¸öÿ¸ô5·ÖÖÓÔËÐÐÒ»´ÎµÄ׼ʱʹÃü£¬ÆäÖÐ /path/to/monitor.sh ÊÇÏÖʵµÄ¼à¿Ø¾ç±¾Â·¾¶¡£
ÉúÑIJ¢Í˳öÎļþ¡£
Ö´ÐÐÉÏÊö²Ù×÷ºó£¬¸ÃʹÃü½«»áÔÚÿ¸ô5·ÖÖÓ×Ô¶¯ÔËÐÐÒ»´Î¼à¿Ø¾ç±¾¡£
¼à¿Ø¾ç±¾Ê¾Àý
ÏÂÃæÊÇÒ»¸ö¼òÆӵļà¿Ø¾ç±¾Ê¾Àý£¬ÓÃÓÚ¼ì²âЧÀÍÆ÷µÄ¸ºÔØÇéÐΣº
#!/bin/bash load=$(uptime | awk '{print $10}') threshold=1.5 if (( $(echo "$load > $threshold" | bc -l) )); then echo "High load detected on server: $load" # ·¢Ë;¯±¨Óʼþ»òÆäËû²Ù×÷ fi
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÊöʾÀýÖУ¬ÎÒÃÇʹÓÃuptimeÏÂÁî»ñȡЧÀÍÆ÷µÄ¸ºÔØÇéÐΣ¬²¢½«ÆäÓëÒ»¸öãÐÖµ¾ÙÐнÏÁ¿¡£ÈôÊǸºÔØÁè¼ÝãÐÖµ£¬¾ç±¾½«»áÊä³öÒ»¸öÖÒÑÔÐÂÎÅ¡£Äú¿ÉÒÔƾ֤ÏÖʵÐèÇóÐ޸ľ籾£¬²¢Ìí¼ÓÆäËûµÄ¼à¿ØÂß¼¡£
½áÂÛ
ͨ¹ýSystemdºÍCrontab£¬ÔÚLinuxϵͳÖÐ×Ô¶¯»¯Ð§ÀÍÆ÷¼à¿Ø³ÉΪÁË¿ÉÄÜ¡£Äú¿ÉÒÔʹÓÃSystemdÀ´½¨ÉèºÍÖÎÀí׼ʱÔËÐеÄЧÀÍ£¬²¢Ê¹ÓÃCrontabÀ´½¨Éè׼ʱʹÃü¡£Í¬Ê±£¬±àдºÏÊʵļà¿Ø¾ç±¾£¬¿ÉÒÔÈÃÄúʵʱ·¢Ã÷DZÔÚµÄÎÊÌâ²¢½ÓÄÉÏìÓ¦µÄ²½·¥¡£
Ï£Íû±¾ÎÄÌṩµÄÐÅÏ¢Äܹ»×ÊÖúÄúÔÚЧÀÍÆ÷¼à¿ØÖÐʵÏÖ×Ô¶¯»¯¡£×£ÄúµÄЧÀÍÆ÷ʼÖÕ¼á³ÖÎȹ̺͸ßЧ£¡
ÒÔÉϾÍÊÇÔõÑùͨ¹ýSystemdºÍCrontabÔÚLinuxϵͳÖÐ×Ô¶¯»¯Ð§ÀÍÆ÷¼à¿ØµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡