Linux中的定时任务:at 和 crontab

时间:2022-06-07 07:58:49

1. 一次性定时任务:at


1.1 设置定时任务

at 命令可以用来执行一次性任务,任务的命令是可以手工输入,也可以从文件读取,语法如下:

NAME
at, batch, atq, atrm - queue, examine or delete jobs for later execution

SYNOPSIS
at [-V] [-q queue] [-f file] [-mMlv] timespec...
at [-V] [-q queue] [-f file] [-mMkv] [-t time]
at -c job [job...]
atq [-V] [-q queue]
at [-rd] job [job...]
atrm [-V] job [job...]
batch
at -b

示例1:手工输入命令
root@db2a:~# at -t 1708182106
warning: commands will be executed using /bin/sh
at> echo "at job is running" >> at.out
at> date >> at.out
at> <EOT> <--这里输入Ctrl+d来结束
job 7 at Fri Aug 18 21:06:00 2017

root@db2a:~# cat at.out
at job is running
Fri Aug 18 21:06:00 PDT 2017

示例2:从文件中读取
root@db2a:~# cat at.sh
#!/bin/sh
echo "I'm a job which called by at command and execute time is:" >> at.sh.out
date >> at.sh.out

root@db2a:~# at -f at.sh -t 1708182112
warning: commands will be executed using /bin/sh
job 10 at Fri Aug 18 21:12:00 2017

root@db2a:~# cat at.sh.out
I'm a job which called by at command and execute time is:
Fri Aug 18 21:12:00 PDT 2017

示例3:从现在开始,三分钟之后执行
root@db2a:~# at -f at.sh now + 3 minutes
warning: commands will be executed using /bin/sh
job 11 at Fri Aug 18 21:24:00 2017

1.2 查看定时任务

查看任务可以使用atq或者al -l,要查询某个具体的任务,可以使用at -c N,其中N表示任务号:
root@db2a:~# atq
11 Fri Aug 18 21:24:00 2017 a root
3 Fri Aug 18 20:48:00 2017 a root

root@db2a:~# at -l
11 Fri Aug 18 21:24:00 2017 a root
3 Fri Aug 18 20:48:00 2017 a root

root@db2a:~# at -c 11
#!/bin/sh
# atrun uid=0 gid=0
# mail qingsong 0
umask 22
XDG_SESSION_ID=8; export XDG_SESSION_ID
USER=root; export USER
...<省略一部分输出>...
MAIL=/var/mail/root; export MAIL
PATH=/home/qingsong/mongodb-linux-x86_64-ubuntu1404-3.4.5/bin/:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin; export PATH
PWD=/root; export PWD
LANG=en_US.UTF-8; export LANG
SHLVL=1; export SHLVL
HOME=/root; export HOME
LANGUAGE=en_US:; export LANGUAGE
LOGNAME=root; export LOGNAME
LESSOPEN=\|\ /usr/bin/lesspipe\ %s; export LESSOPEN
XDG_RUNTIME_DIR=/run/user/1000; export XDG_RUNTIME_DIR
LESSCLOSE=/usr/bin/lesspipe\ %s\ %s; export LESSCLOSE
OLDPWD=/etc; export OLDPWD
cd /root || {
echo 'Execution directory inaccessible' >&2
exit 1
}
#!/bin/sh
echo "I'm a job which called by at command and execute time is:" >> at.sh.out
date >> at.sh.out

1.3 删除定时任务

使用at -d N或者atrm来删除任务,其中N为任务号
root@db2a:~# at -d 3

2. 定期循环任务:crontab


2.1 设置定期循环任务

可以使用crontab来设置定期性循环任务,可以指定任务执行的分钟、小时、日期、月份、年份、周几, 语法如下:
SYNOPSIS
crontab [ -u user ] file
crontab [ -u user ] [ -i ] { -e | -l | -r }

发出crontab -e命令后,会让选择一个编辑器,在里面每新增加一行,就多一个任务
root@db2a:~# crontab -e
no crontab for root - using an empty one

Select an editor. To change later, run 'select-editor'.
1. /bin/ed
2. /bin/nano <---- easiest
3. /usr/bin/vim.basic
4. /usr/bin/vim.tiny

Choose 1-4 [2]: 3
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command

每个任务 (每行) 的格式都是具有六个字段,这六个字段的意义分别为:
意义 分钟 小时 日期 月份 周 命令
范围
0-59 0-23 1-31 1-12 0-7 具体命令

另外,"*"代表全部,","隔开多个值,"-"代表一个时间段,"/"代表每隔固定时间,示例如下:
每年的12月31号,每个整点执行一次脚本/root/cron.sh:
0 * 31 12 * /root/cron.sh

每天的0点和12点整执行脚本/root/cron.sh
0 0,12 * * * /root/cron.sh

每周一到周五上午8点执行脚本/root/cron.sh
0 8 * * 1-5 /root/cron.sh

每隔5分钟执行一次脚本/root/cron.sh
*/5 * * * * /root/cron.sh
或者
0-59/5 * * * * /root/cron.sh

2.2 查看定期任务

crontab -l

2.3 删除定期任务

删除crontab,注意,下面的命令会删除所有的条目,如果想要删除一部分,则使用crontab -e去编辑
crontab -r

另外,有几个需要注意的地方:
1. 不能同时指定周与日月,也就是说,如果指定了具体日期,就不要指定周几了。
2. 分钟这一栏,如果不希望每分钟一次,则一定要指定;如果为 *,则每分钟都要执行一次

附上at和crontab的详细说明:

NAME
       at, batch, atq, atrm - queue, examine or delete jobs for later execution

SYNOPSIS
       at [-V] [-q queue] [-f file] [-mMlv] timespec...
       at [-V] [-q queue] [-f file] [-mMkv] [-t time]
       at -c job [job...]
       atq [-V] [-q queue]
       at [-rd] job [job...]
       atrm [-V] job [job...]
       batch
       at -b

DESCRIPTION
       at  and  batch read commands from standard input or a specified file which are to be executed at a later time,
       using /bin/sh.

       at      executes commands at a specified time.

       atq     lists the user's pending jobs, unless the user is the superuser; in that case,  everybody's  jobs  are
               listed.   The  format  of  the  output lines (one for each job) is: Job number, date, hour, queue, and
               username.

       atrm    deletes jobs, identified by their job number.

       batch   executes commands when system load levels permit; in other words, when the load  average  drops  below
               1.5, or the value specified in the invocation of atd.

       At  allows  fairly  complex time specifications, extending the POSIX.2 standard.  It accepts times of the form
       HH:MM to run a job at a specific time of day.  (If that time is already past, the next day is  assumed.)   You
       may  also  specify  midnight, noon, or teatime (4pm) and you can have a time-of-day suffixed with AM or PM for
       running in the morning or the evening.  You can also say what day the job will be run, by giving a date in the
       form month-name day with an optional year, or giving a date of the form MMDD[CC]YY, MM/DD/[CC]YY, DD.MM.[CC]YY
       or [CC]YY-MM-DD.  The specification of a date must follow the specification of the time of day.  You can  also
       give times like now + count time-units, where the time-units can be minutes, hours, days, or weeks and you can
       tell at to run the job today by suffixing the time with today and to run the job  tomorrow  by  suffixing  the
       time with tomorrow.

       For example, to run a job at 4pm three days from now, you would do at 4pm + 3 days, to run a job at 10:00am on
       July 31, you would do at 10am Jul 31 and to run a job at 1am tomorrow, you would do at 1am tomorrow.

       The definition of the time specification can be found in /usr/share/doc/at/timespec.

       For both at and batch, commands are read from standard input or the file specified with the -f option and exe鈥[m
       cuted.  The working directory, the environment (except for the variables BASH_VERSINFO, DISPLAY, EUID, GROUPS,
       SHELLOPTS, TERM, UID, and _) and the umask are retained from the time of invocation.

       As at is currently implemented as a setuid program, other  environment  variables  (e.g.   LD_LIBRARY_PATH  or
       LD_PRELOAD)  are  also  not  exported.   This  may change in the future.  As a workaround, set these variables
       explicitly in your job.

       An at - or batch - command invoked from a su(1) shell will retain the current userid.  The user will be mailed
       standard  error  and  standard  output  from  his  commands,  if  any.   Mail  will  be sent using the command
       /usr/sbin/sendmail.  If at is executed from a su(1) shell, the owner of the login shell will receive the mail.

       The superuser may use these commands in any case.  For other users, permission to use at is determined by  the
       files /etc/at.allow and /etc/at.deny.  See at.allow(5) for details.

OPTIONS
       -V      prints the version number to standard error and exit successfully.

       -q queue
               uses  the  specified queue.  A queue designation consists of a single letter; valid queue designations
               range from a to z and A to Z.  The a queue is the default for at and the b queue  for  batch.   Queues
               with higher letters run with increased niceness.  The special queue "=" is reserved for jobs which are
               currently running.

       If a job is submitted to a queue designated with an uppercase letter, the job is treated as if it were submit鈥[m
       ted  to  batch  at  the time of the job.  Once the time is reached, the batch processing rules with respect to
       load average apply.  If atq is given a specific queue, it will only show jobs pending in that queue.

       -m      Send mail to the user when the job has completed even if there was no output.

       -M      Never send mail to the user.

       -f file Reads the job from file rather than standard input.

       -t time run the job at time, given in the format [[CC]YY]MMDDhhmm[.ss]

       -l      Is an alias for atq.

       -r      Is an alias for atrm.

       -d      Is an alias for atrm.

       -b      is an alias for batch.

       -v      Shows the time the job will be executed before reading the job.

       Times displayed will be in the format "Thu Feb 20 14:50:00 1997".

       -c     cats the jobs listed on the command line to standard output.

FILES
       /var/spool/cron/atjobs
       /var/spool/cron/atspool
       /proc/loadavg
       /var/run/utmp
       /etc/at.allow
       /etc/at.deny

SEE ALSO
       at.allow(5), at.deny(5), atd(8), cron(1), nice(1), sh(1), umask(2).

BUGS
       The correct operation of batch for Linux depends on the presence of a proc- type directory mounted on /proc.

       If the file /var/run/utmp is not available or corrupted, or if the user is not logged on at  the  time  at  is
       invoked,  the  mail  is sent to the userid found in the environment variable LOGNAME.  If that is undefined or
       empty, the current userid is assumed.

       At and batch as presently implemented are not suitable when users are competing for resources.  If this is the
       case for your site, you might want to consider another batch system, such as nqs.

AUTHOR
       At was mostly written by Thomas Koenig, ig25@rz.uni-karlsruhe.de.

CRONTAB(1)                                            General Commands Manual                                           CRONTAB(1)

NAME
       crontab - maintain crontab files for individual users (Vixie Cron)

SYNOPSIS
       crontab [ -u user ] file
       crontab [ -u user ] [ -i ] { -e | -l | -r }

DESCRIPTION
       crontab  is the program used to install, deinstall or list the tables used to drive the cron(8) daemon in Vixie Cron.  Each
       user can have their own crontab, and though these are files in /var/spool/cron/crontabs, they are not intended to be edited
       directly.

       If  the /etc/cron.allow file exists, then you must be listed (one user per line) therein in order to be allowed to use this
       command.  If the /etc/cron.allow file does not exist but the /etc/cron.deny file does exist, then you must not be listed in
       the /etc/cron.deny file in order to use this command.

       If  neither  of  these files exists, then depending on site-dependent configuration parameters, only the super user will be
       allowed to use this command, or all users will be able to use this command.

       If both files exist then /etc/cron.allow takes precedence. Which means that /etc/cron.deny is not considered and your  user
       must be listed in /etc/cron.allow in order to be able to use the crontab.

       Regardless  of the existance of any of these files, the root administrative user is always allowed to setup a crontab.  For
       standard Debian systems, all users may use this command.

       If the -u option is given, it specifies the name of the user whose crontab is to be used (when listing) or  modified  (when
       editing).  If this option is not given, crontab examines "your" crontab, i.e., the crontab of the person executing the com鈥[m
       mand.  Note that su(8) can confuse crontab and that if you are running inside of su(8) you should always use the -u  option
       for safety's sake.

       The  first form of this command is used to install a new crontab from some named file or standard input if the pseudo-file鈥[m
       name ``-'' is given.

       The -l option causes the current crontab to be displayed on standard output. See the note under DEBIAN SPECIFIC below.

       The -r option causes the current crontab to be removed.

       The -e option is used to edit the current crontab using the editor specified by the VISUAL or EDITOR environment variables.
       After  you  exit from the editor, the modified crontab will be installed automatically. If neither of the environment vari鈥[m
       ables is defined, then the default editor /usr/bin/editor is used.

       The -i option modifies the -r option to prompt the user for a 'y/Y' response before actually removing the crontab.

DEBIAN SPECIFIC
       The "out-of-the-box" behaviour for crontab -l is to display the three line "DO NOT EDIT THIS FILE" header that is placed at
       the beginning of the crontab when it is installed. The problem is that it makes the sequence

       crontab -l | crontab -

       non-idempotent  -- you keep adding copies of the header. This causes pain to scripts that use sed to edit a crontab. There鈥[m
       fore, the default behaviour of the -l option has been changed to not output such header. You may obtain the original behav鈥[m
       iour  by  setting  the  environment  variable  CRONTAB_NOHEADER to 'N', which will cause the crontab -l command to emit the
       extraneous header.

SEE ALSO
       crontab(5), cron(8)

FILES
       /etc/cron.allow
       /etc/cron.deny
       /var/spool/cron/crontabs

       There is one file for each user's crontab under the /var/spool/cron/crontabs directory. Users are not allowed to  edit  the
       files under that directory directly to ensure that only users allowed by the system to run periodic tasks can add them, and
       only syntactically correct crontabs will be written there.  This is enforced by having the directory writable only  by  the
       crontab group and configuring crontab command with the setgid bid set for that specific group.

STANDARDS
       The crontab command conforms to IEEE Std1003.2-1992 (``POSIX'').  This new command syntax differs from previous versions of
       Vixie Cron, as well as from the classic SVR3 syntax.

DIAGNOSTICS
       A fairly informative usage message appears if you run it with a bad command line.

       cron requires that each entry in a crontab end in a newline character. If the last entry in a crontab is missing  the  new鈥[m
       line, cron will consider the crontab (at least partially) broken and refuse to install it.

AUTHOR
       Paul  Vixie <paul@vix.com> is the author of cron and original creator of this manual page. This page has also been modified
       for Debian by Steve Greenland, Javier Fernandez-Sanguino and Christian Kastner.