LinuxϵͳÖÐʹÓÃSystemdºÍCrontabʵÏÖ׼ʱʹÃüÖÎÀíµÄ×î¼Ñʵ¼ù
LinuxϵͳÖÐʹÓÃSystemdºÍCrontabʵÏÖ׼ʱʹÃüÖÎÀíµÄ×î¼Ñʵ¼ù
СÐò£º
ÔÚLinuxϵͳÖУ¬×¼Ê±Ê¹ÃüµÄÖÎÀí¹ØÓÚϵͳµÄÎȹ̺͸ßЧÔËÐкÜÊÇÖ÷Òª¡£ÎªÁËʵÏÖ׼ʱʹÃüµÄ×Ô¶¯»¯Ö´ÐУ¬LinuxϵͳÌṩÁ˶àÖÖ¹¤¾ß£¬ÆäÖÐ×î³£ÓõÄÊÇSystemdºÍCrontab¡£±¾ÎĽ«ÏÈÈÝÔõÑùʹÓÃSystemdºÍCrontab¾ÙÐÐ׼ʱʹÃüÖÎÀí£¬²¢¸ø³öÏêϸµÄ´úÂëʾÀý¡£
Ò»¡¢SystemdµÄ׼ʱʹÃüÖÎÀí
SystemdÊÇÏÖÔڴ󲿷ÖLinux¿¯ÐаæĬÈÏʹÓõijõʼ»¯ÏµÍ³£¬ËüÌṩÁ˶ÔϵͳÆô¶¯Àú³ÌµÄÍêÈ«¿ØÖÆ£¬²¢ÇÒ¿ÉÒÔÓÃÓÚÖÎÀíÖÖÖÖϵͳЧÀͺÍ׼ʱʹÃü¡£ÏÂÃæÊÇʹÓÃSystemdʵÏÖ׼ʱʹÃüÖÎÀíµÄ×î¼Ñʵ¼ù¡£
½¨ÉèЧÀÍÎļþ£º
Ê×ÏÈ£¬ÎÒÃÇÐèÒª½¨ÉèÒ»¸öSystemdЧÀÍÎļþ£¬ºó׺ÃûΪ.service¡£ÔÚЧÀÍÎļþÖнç˵׼ʱʹÃüµÄÃû³Æ¡¢ÐÎò¡¢Ö´ÐгÌÐò·¾¶¡¢ÔËÐвÎÊýµÈÏà¹ØÐÅÏ¢¡£ÒÔÖ´ÐÐÒ»¸öShell¾ç±¾×¼Ê±É¾³ýÖ¸¶¨Ä¿Â¼ÏµÄÎļþΪÀý£¬ÎÒÃÇ¿ÉÒÔ½¨ÉèÒ»¸öÃûΪclean_dir.serviceµÄЧÀÍÎļþ£¬ÏêϸÄÚÈÝÈçÏ£º
[Unit] Description=׼ʱÕûÀíĿ¼ÏµÄÎļþ [Service] ExecStart=/bin/bash /usr/local/scripts/clean_dir.sh
µÇ¼ºó¸´ÖÆ
½¨ÉèShell¾ç±¾£º
½ÓÏÂÀ´£¬ÎÒÃÇÐèÒª±àдһ¸öShell¾ç±¾£¬¸Ã¾ç±¾½«ÊµÏÖ׼ʱʹÃüµÄÏêϸ²Ù×÷Âß¼¡£ÒÔɾ³ýÖ¸¶¨Ä¿Â¼ÏµÄÎļþΪÀý£¬ÎÒÃÇ¿ÉÒÔ½¨ÉèÒ»¸öÃûΪclean_dir.shµÄShell¾ç±¾£¬ÏêϸÄÚÈÝÈçÏ£º
#!/bin/bash DIR_PATH="/path/to/directory" find $DIR_PATH -type f -mtime +7 -exec rm -f {} ;
µÇ¼ºó¸´ÖÆ
ÆôÓúÍÖÎÀíЧÀÍ£º
Íê³ÉÉÏÊöÁ½²½ºó£¬ÎÒÃÇ¿ÉÒÔͨ¹ýÒÔÏÂÏÂÁîÆôÓúÍÖÎÀí׼ʱʹÃüЧÀÍ£º
$ sudo cp clean_dir.service /etc/systemd/system/ $ sudo systemctl daemon-reload $ sudo systemctl enable clean_dir.service $ sudo systemctl start clean_dir.service $ sudo systemctl status clean_dir.service
µÇ¼ºó¸´ÖÆ
ͨ¹ýÒÔÉÏÏÂÁÎÒÃǽ«Ð§ÀÍÎļþ¿½±´µ½/systemd/systemĿ¼Ï£¬ÖØмÓÔØSystemdÉèÖã¬ÆôÓò¢Æô¶¯×¼Ê±Ê¹ÃüЧÀÍ£¬²¢¼ì²éÆä״̬¡£
¶þ¡¢CrontabµÄ׼ʱʹÃüÖÎÀí
CrontabÊÇÒ»¸ö׼ʱʹÃüµ÷Àí³ÌÐò£¬Ëü¿ÉÒÔÔÚÖ¸¶¨µÄʱ¼ä¾àÀëÄÚÔËÐÐÌض¨µÄÏÂÁî»ò¾ç±¾¡£ÏÂÃæÊÇʹÓÃCrontabʵÏÖ׼ʱʹÃüÖÎÀíµÄ×î¼Ñʵ¼ù¡£
±à¼CrontabÉèÖãº
Ê×ÏÈ£¬ÎÒÃÇÐèÒª±à¼CrontabÉèÖÃÎļþ£¬Ê¹ÓÃÒÔÏÂÏÂÁî·¿ªCrontab±à¼Æ÷£º
$ crontab -e
µÇ¼ºó¸´ÖÆ
Ìí¼Ó׼ʱʹÃü£º
ÔÚCrontab±à¼Æ÷ÖУ¬ÎÒÃÇ¿ÉÒÔÌí¼Ó׼ʱʹÃü£¬Ö¸¶¨Ê¹ÃüµÄÖ´ÐÐʱ¼ä¡¢Ö´ÐеÄÏÂÁî»ò¾ç±¾µÈ¡£ÒÔÖ´ÐÐÒ»¸öShell¾ç±¾×¼Ê±±¸·ÝÊý¾Ý¿âΪÀý£¬ÎÒÃÇ¿ÉÒÔÔÚCrontab±à¼Æ÷ÖÐÌí¼ÓÈçÏÂÄÚÈÝ£º
0 * /bin/bash /usr/local/scripts/backup_db.sh
ÉÏÊöʾÀýÌåÏÖÌìÌìµÄ0µã0·Ö£¬Ö´ÐÐ/usr/local/scripts/backup_db.sh¾ç±¾¡£
µÇ¼ºó¸´ÖÆ
ÉúÑĺÍÉó²éÉèÖãº
Ìí¼ÓÍê׼ʱʹÃüºó£¬ÎÒÃÇÐèÒªÉúÑIJ¢Í˳öCrontab±à¼Æ÷¡£Crontab½«×Ô¶¯ÉúÑÄÎÒÃǵÄÉèÖ㬲¢×îÏÈƾָ֤¶¨µÄʱ¼ä¾àÀëÖ´ÐÐʹÃü¡£¿ÉÒÔʹÓÃÒÔÏÂÏÂÁîÉó²éÄ¿½ñÓû§µÄCrontabÉèÖãº
$ crontab -l
µÇ¼ºó¸´ÖÆ
×ܽ᣺
±¾ÎÄÏÈÈÝÁËʹÓÃSystemdºÍCrontabʵÏÖ׼ʱʹÃüÖÎÀíµÄ×î¼Ñʵ¼ù£¬²¢¸ø³öÁËÏêϸµÄ´úÂëʾÀý¡£Ê¹ÓÃSystemd¿ÉÒÔÎÞа¿ØÖƺÍÖÎÀí׼ʱʹÃüЧÀÍ£¬Ê¹ÓÃCrontab¿ÉÒÔ¿ìËÙÀû±ãµØÌí¼ÓºÍÖÎÀí׼ʱʹÃü¡£Í¨¹ýºÏÀíʹÓÃÕâÁ½ÖÖ¹¤¾ß£¬ÎÒÃÇ¿ÉÒÔʵÏÖLinuxϵͳÖеÄ׼ʱʹÃü×Ô¶¯»¯Ö´ÐУ¬Ìá¸ßϵͳµÄÎȹÌÐÔºÍÊÂÇéЧÂÊ¡£
×¢ÖØ£º
Çëƾ֤ÏÖʵÐèÇóÐ޸ĴúÂëʾÀýÖеÄÎļþ·¾¶ºÍ¾ç±¾ÄÚÈÝ£¬È·±£²Ù×÷µÄ׼ȷÐÔºÍÇå¾²ÐÔ¡£
ÒÔÉϾÍÊÇLinuxϵͳÖÐʹÓÃSystemdºÍCrontabʵÏÖ׼ʱʹÃüÖÎÀíµÄ×î¼Ñʵ¼ùµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡