Home >Operation and Maintenance >Linux Operation and Maintenance >How to execute tasks regularly in Linux

How to execute tasks regularly in Linux

王林
王林forward
2023-05-13 19:01:0415989browse

    1 Tutorial

    1.1 Install crontabs

    yum install contabs  #通过yum安装
    systemctl enable crond  #设置开机启动
    systemctl start crond   #启动

    1.2 Check the status of crontab service:

    service crond status

    How to execute tasks regularly in Linux

    1.3 Check the crontab log information

    tail -f /var/log/cron  #crontab的日志信息放在/var/log文件夹中
    cat  /vat/log/cron

    How to execute tasks regularly in Linux

    In the process of crontab executing the script regularly, there may be files Permission issues, such as:

    How to execute tasks regularly in Linux

    At this time, you need to give the script executed by the scheduled task an executable permission. The command to modify the permissions is as follows:

    chmod 777 /home/centos/sh/test.sh  #给所有权限

    1.4 Configure scheduled tasks

    The scheduled task file of crontab is placed in the /etc/crontab file, and can be modified directly using vim Can:

    How to execute tasks regularly in Linux

    ##/etc/crontabThe default content of the file is as follows, which also explains what each symbol means:

    SHELL=/bin/bash
    PATH=/sbin:/bin:/usr/sbin:/usr/bin
    MAILTO=HOME=/
    # run-parts
    51 * * * * root run-parts /etc/cron.hourly
    24 7 * * * root run-parts /etc/cron.daily
    22 4 * * 0 root run-parts /etc/cron.weekly
    42 4 1 * * root run-parts /etc/cron.monthly

    The first four lines are used to configure the environment variables for crond task running. The SHELL variable in the first line specifies which shell the system should use, here is bash. The PATH variable in the second line specifies the path for the system to execute the command. The MAILTO variable in the third line specifies The task execution information of crond will be sent to the root user via email. If the value of the MAILTO variable is empty, it means that the task execution information will not be sent to the user. The HOME variable in the fourth line specifies the homepage used when executing the command or script. Table of contents. The meanings represented by lines six to nine will be described in detail in the next section.

    在以上各个字段中,还可以使用以下特殊字符:
    星号(*):代表所有可能的值,例如month字段如果是星号,则表示在满足其它字段的制约条件后每月都执行该命令操作。
    逗号(,):可以用逗号隔开的值指定一个列表范围,例如,“1,2,5,7,8,9”
    中杠(-):可以用整数之间的中杠表示一个整数范围,例如“2-6”表示“2,3,4,5,6”
    正斜线(/):可以用正斜线指定时间的间隔频率,例如“0-23/2”表示每两小时执行一次。同时正斜线可以和星号一起使用,例如*/10,如果用在minute字段,表示每十分钟执行一次。
    文件:
    /etc/cron.deny
    说明:
    该文件中所列用户不允许使用crontab命令
    
    文件:
    /etc/cron.allow
    说明:
    该文件中所列用户允许使用crontab命令
    
    文件:
    /var/spool/cron/
    说明:
    所有用户crontab文件存放的目录,以用户名命名
    
    crontab文件的含义:
    用户所建立的crontab文件中,每一行都代表一项任务,每行的每个字段代表一项设置,它的格式共分为六个字段,前五段是时间设定段,第六段是要执行的命令段,格式如下:
    minute hour day month week command
    
    其中:
    minute: 表示分钟,可以是从0到59之间的任何整数。
    hour:表示小时,可以是从0到23之间的任何整数。
    day:表示日期,可以是从1到31之间的任何整数。
    month:表示月份,可以是从1到12之间的任何整数。
    week:表示星期几,可以是从0到7之间的任何整数,这里的0或7代表星期日。
    command:要执行的命令,可以是系统命令,也可以是自己编写的脚本文件。

    How to execute tasks regularly in Linux

    • First position: minutes (0-59)

    • Second position: Hour (0-23)

    • Third position: Day (1-31)

    • Fourth position: Month (1- 12)

    • The fifth position: week (0-6)

    • The sixth position: username

    • Seventh position: Scripts or commands that need to be executed regularly

    (1) Modify scheduled tasks:
    crontab -e  #该命令等同于  vim /etc/crontab
    (2) View scheduled tasks
    crontab -l  #该命令等同于 cat /etc/crontab
    1.5 Detailed explanation of crontab command

    1.5.1 Command format
    crontab [-u user] file
    crontab [-u user] [ -e | -l | -r ]
    1.5.2 Command function
    With the crontab command, we can Execute the specified system command or shell script at the time. The unit of time interval can be minutes, hours, days, months, weeks, or any combination of above. This command is very suitable for periodic log analysis or data backup and other tasks.

    1.5.3 Command parameters
    • #-u user: used to set the crontab service of a certain user, for example, “-u ixdba "Indicates setting the crontab service of the ixdba user. This parameter is generally run by the root user.

    • file: file is the name of the command file, which means that file is used as the task list file of crontab and loaded into crontab. If this file is not specified on the command line, the crontab command will accept commands typed on standard input (keyboard) and load them into crontab.

    • -e: Edit the contents of a user's crontab file. If no user is specified, it means editing the crontab file of the current user.

    • -l: Display the crontab file content of a certain user. If the user is not specified, it means displaying the crontab file content of the current user.

    • -r: Delete a user's crontab file from the /var/spool/cron directory. If no user is specified, the current user's crontab will be deleted by default. document.

    • -i: Give a confirmation prompt when deleting the user's crontab file.

    1.5.4 Common methods
    Create a new crontab file

    The first thing to do before considering submitting a crontab file to the cron process One thing is to set the environment variable EDITOR. The cron process uses it to determine which editor to use to edit the crontab file. 99% of UNIX and LINUX users use vi. If this is the case for you, then edit the .profile file in the $HOME directory and add this line to it:

    EDITOR=vi; export EDITOR

    Then save and exit. Might as well create a file called cron where is the username, for example, davecron. Add the following content to this file.

    # (put your own initials here)echo the date to the console every
    # 15minutes between 6pm and 6am
    0,15,30,45 18-06 * /bin/echo ‘date' > /dev/console

    Save and exit. Make sure the first 5 fields are separated by spaces.

    In the above example, the system will output the current time to the console every 15 minutes. If the system crashes or hangs, the last time displayed will tell you at a glance when the system stopped working. In some systems, tty1 is used to represent the console, and the above example can be modified accordingly according to the actual situation. In order to submit the crontab file you just created, you can use this newly created file as a parameter of the cron command:

    $ crontab davecron

    • 现在该文件已经提交给cron进程,它将每隔15分钟运行一次。

      同时,新创建文件的一个副本已经被放在/var/spool/cron目录中,文件名就是用户名(即dave)。

    • 列出crontab文件

      为了列出crontab文件,可以用:

    $ crontab -l
    0,15,30,45,18-06 * * * /bin/echo`date`> dev/tty1

    你将会看到和上面类似的内容。可以使用这种方法在$ H O M E目录中对crontab文件做一备份:

    $ crontab -l > $HOME/mycron
    • 这样,一旦不小心误删了crontab文件,可以用上一节所讲述的方法迅速恢复。

    • 编辑crontab文件

      如果希望添加、删除或编辑crontab文件中的条目,而E D I TO R环境变量又设置为vi,那么就可以用vi来编辑crontab文件,相应的命令为:

    $ crontab -e

    可以像使用v i编辑其他任何文件那样修改crontab文件并退出。如果修改了某些条目或添加了新的条目,那么在保存该文件时, cron会对其进行必要的完整性检查。如果其中的某个域出现了超出允许范围的值,它会提示你。

    我们在编辑crontab文件时,没准会加入新的条目。例如,加入下面的一条:

    # DT:delete core files,at 3.30am on 1,7,14,21,26,26 days of each month
    30 3 1,7,14,21,26 /bin/find -name “core' -exec rm {} \;

    现在保存并退出。最好在crontab文件的每一个条目之上加入一条注释,这样就可以知道它的功能、运行时间,更为重要的是,知道这是哪位用户的作业。

    现在让我们使用前面讲过的crontab -l命令列出它的全部信息:

    $ crontab -l
    # (crondave installed on Tue May 4 13:07:43 1999)
    # DT:ech the date to the console every 30 minites
    0,15,30,45 18-06 * * * /bin/echo`date`> /dev/tty1
    # DT:delete core files,at 3.30am on 1,7,14,21,26,26 days of each month
    30 3 1,7,14,21,26 * * /bin/find -name “core' -exec rm {} \;

    删除crontab文件

    要删除crontab文件,可以用:

    $ crontab -r

    恢复丢失的crontab文件

    如果不小心误删了crontab文件,假设你在自己的$HOME目录下还有一个备份,那么可以将其拷贝到/var/spool/cron/,其中是用户名。如果由于权限问题无法完成拷贝,可以用:

    $ crontab

    其中,是你在$HOME目录中副本的文件名。

    我建议你在自己的$HOME目录中保存一个该文件的副本。我就有过类似的经历,有数次误删了crontab文件(因为r键紧挨在e键的右边)。这就是为什么有些系统文档建议不要直接编辑crontab文件,而是编辑该文件的一个副本,然后重新提交新的文件。

    有些crontab的变体有些怪异,所以在使用crontab命令时要格外小心。如果遗漏了任何选项,crontab可能会打开一个空文件,或者看起来像是个空文件。这时敲delete键退出,不要按,否则你将丢失crontab文件。

    2 案例

    (1)每5秒执行一次任务

    */1 * * * * /bin/date >>/tmp/date.txt
    */1 * * * * sleep 5  && /bin/date >>/tmp/date.txt
    */1 * * * * sleep 10 && /bin/date >>/tmp/date.txt
    */1 * * * * sleep 15 && /bin/date >>/tmp/date.txt
    */1 * * * * sleep 20 && /bin/date >>/tmp/date.txt
    */1 * * * * sleep 25 && /bin/date >>/tmp/date.txt
    */1 * * * * sleep 30 && /bin/date >>/tmp/date.txt
    */1 * * * * sleep 35 && /bin/date >>/tmp/date.txt
    */1 * * * * sleep 40 && /bin/date >>/tmp/date.txt
    */1 * * * * sleep 45 && /bin/date >>/tmp/date.txt
    */1 * * * * sleep 50 && /bin/date >>/tmp/date.txt
    */1 * * * * sleep 55 && /bin/date >>/tmp/date.txt

    (2)更多案例

    实例1:每1分钟执行一次command
    命令:
    * * * * * command
    
    实例2:每小时的第3和第15分钟执行
    命令:
    3,15 * * * * command
    
    实例3:在上午8点到11点的第3和第15分钟执行
    命令:
    3,15 8-11 * * * command
    
    实例4:每隔两天的上午8点到11点的第3和第15分钟执行
    命令:
    3,15 8-11 */2 * * command
    
    实例5:每个星期一的上午8点到11点的第3和第15分钟执行
    命令:
    3,15 8-11 * * 1 command
    
    实例6:每晚的21:30重启smb
    命令:
    30 21 * * * /etc/init.d/smb restart
    
    实例7:每月1、10、22日的4 : 45重启smb
    命令:
    45 4 1,10,22 * * /etc/init.d/smb restart
    
    实例8:每周六、周日的1 : 10重启smb
    命令:
    10 1 * * 6,0 /etc/init.d/smb restart
    
    实例9:每天18 : 00至23 : 00之间每隔30分钟重启smb
    命令:
    0,30 18-23 * * * /etc/init.d/smb restart
    
    实例10:每星期六的晚上11 : 00 pm重启smb
    命令:
    0 23 * * 6 /etc/init.d/smb restart
    
    实例11:每一小时重启smb
    命令:
    * */1 * * * /etc/init.d/smb restart
    
    实例12:晚上11点到早上7点之间,每隔一小时重启smb
    命令:
    * 23-7/1 * * * /etc/init.d/smb restart
    
    实例13:每月的4号与每周一到周三的11点重启smb
    命令:
    0 11 4 * mon-wed /etc/init.d/smb restart
    
    实例14:一月一号的4点重启smb
    命令:
    0 4 1 jan * /etc/init.d/smb restart
    
    实例15:每小时执行/etc/cron.hourly目录内的脚本
    命令:
    01 * * * * root run-parts /etc/cron.hourly
    说明:
    run-parts这个参数了,如果去掉这个参数的话,后面就可以写要运行的某个脚本名,而不是目录名了

    (3) 使用注意

    注意环境变量问题
    有时我们创建了一个crontab,但是这个任务却无法自动执行,而手动执行这个任务却没有问题,这种情况一般是由于在crontab文件中没有配置环境变量引起的。

    在 crontab文件中定义多个调度任务时,需要特别注意的一个问题就是环境变量的设置,因为我们手动执行某个任务时,是在当前shell环境下进行的,程 序当然能找到环境变量,而系统自动执行任务调度时,是不会加载任何环境变量的,因此,就需要在crontab文件中指定任务运行所需的所有环境变量,这 样,系统执行任务调度时就没有问题了。

    不要假定cron知道所需要的特殊环境,它其实并不知道。所以你要保证在shelll脚本中提供所有必要的路径和环境变量,除了一些自动设置的全局变量。所以注意如下3点:

    脚本中涉及文件路径时写全局路径;

    脚本执行要用到java或其他环境变量时,通过source命令引入环境变量,如:

    cat start_cbp.sh
    #!/bin/sh
    source /etc/profile
    export RUN_CONF=/home/d139/conf/platform/cbp/cbp_jboss.conf
    /usr/local/jboss-4.0.5/bin/run.sh -c mev &
    • 当手动执行脚本OK,但是crontab死活不执行时。这时必须大胆怀疑是环境变量惹的祸,并可以尝试在crontab中直接引入环境变量解决问题。如:

    0 . /etc/profile;/bin/sh /var/www/java/audit_no_count/bin/restart_audit.sh

    注意清理系统用户的邮件日志
    每条任务调度执行完毕,系统都会将任务输出信息通过电子邮件的形式发送给当前系统用户,这样日积月累,日志信息会非常大,可能会影响系统的正常运行,因此,将每条任务进行重定向处理非常重要。

    例如,可以在crontab文件中设置如下形式,忽略日志输出:

    0 */3* /usr/local/apache2/apachectl restart >/dev/null 2>&1

    /dev/null 2>&1表示先将标准输出重定向到/dev/null,然后将标准错误重定向到标准输出,由于标准输出已经重定向到了/dev/null,因此标准错误也会重定向到/dev/null,这样日志输出问题就解决了。

    System-level task scheduling and user-level task scheduling
    System-level task scheduling mainly completes some maintenance operations of the system. User-level task scheduling mainly completes some user-defined tasks. User-level task scheduling can be placed at the system level. Task scheduling is done through task scheduling (not recommended), but the reverse does not work. The root user's task scheduling operation can be set through crontab –uroot –e, or the scheduled task can be written directly to /etc /crontab file, it should be noted that if you want to define a task to restart the system regularly, you must put the task in the /etc/crontab file, even if you create one under the root user The task of regularly restarting the system is also invalid.

    Other Notes
    The newly created cron job will not be executed immediately and will take at least 2 minutes to execute. If cron is restarted, it will be executed immediately.

    When crontab suddenly fails, you can try /etc/init.d/crond restart to solve the problem. Or check the log to see if a job has been executed/reported an errortail -f /var/log/cron.

    Don’t run crontab -r randomly. It deletes the user's Crontab files from the Crontab directory (/var/spool/cron). All crontabs of the user are gone after deletion.

    % has a special meaning in crontab, which means line break. If you want to use it, you must escape \%. For example, the frequently used date ' %Y%m%d' will not be executed in crontab and should be replaced with date ' \%Y \%m\%d'.

    The above is the detailed content of How to execute tasks regularly in Linux. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete