天天看点

【LINUX学习】例行命令的建立

例行命令就是那些需要定期执行的命令或者某个脚本。在linux中一般使用at 和contable服务来实现。

下面就简要的介绍一下两个的大概使用方法

at :此服务仅仅执行一次,之后就从linux中取消

先查看一下at服务的状态

[root@localhost test]# service atd status

atd (pid 2222) 正在运行...

停止服务

[root@localhost test]# service atd stop

停止 atd:[确定] 

启动服务

[root@localhost test]# service atd start

启动 atd:[确定]

设置开机时自动启动

[root@localhost test]# chkconfig --level 35 atd on

取消开机时自动启动

[root@localhost test]# chkconfig --level 35 atd off

[root@localhost test]# ls

yang.txt

设置2分钟后 删除test目录里面的yang,txt 文件

[root@localhost test]# at now + 2 minutes

at> rm -f yang.txt

at>

job 5 at 2010-11-26 20:10

查询当前主机上有多少的at 服务

[root@localhost test]# atq

5       2010-11-26 20:10 a root --5 代表编号,之前我做了测试。

上面说 在2010-11-26 20:10 有一个定时工作 设置该工作的是root ,编号为5

[root@localhost test]# atq 

过了两分钟以后 查看test 目录和 at服务  ,可以看见yang.txt 文件被删除了,而且at服务也没有了。当然如果设置at 服务错误或者想要撤销,可以执行如下语句:

[root@localhost test]# at now + 4 minutes

at> cp yant^h                    -我设置了一个错误的例子。

job 6 at 2010-11-26 20:17

6       2010-11-26 20:17 a root  --这次编号变为6

[root@localhost test]# atrm 6  --atrm 后面跟 jobnumber  意为删除该工作。

[root@localhost test]# atq  --再次查询 编号为6的 at 服务被删除了。

[root@localhost test]# 

---至此 at 服务的使用方法结束。更多的at ,atq ,atrm 使用方法请参考man。

cron: 此服务将循环进行。

相对于at 一次性执行服务,多次循环工作的工作就由cron这个系统服务来完成的。

linux提供了crontab 命令 来实现 例行工作。

使用者要想使用crontab 的使用者是由一下文件决定 的;

/etc/cron.allow: 

将可以使用cron服务的帐号写入该文件,若不在该文件的使用者则不能使用cron服务 

/etc/cron.deny

将禁止使用cron服务的帐号写入该文件,若不在该文件的使用者则能使用cron服务

<b>当然 如果不存在以上两个文件的话 就只有root用户可以使用cron服务</b>。cron.allow 比cron.deny 优先,一般这两个文件只使用一个就可以了。一般来说系统保留cron.deny 。

下面介绍一下crontab的使用方法:

启动与关闭服务与at 一样,只是服务名称不同罢了。因此,偶将此省略了。

[root@localhost test]# crontab -l  --

no crontab for root

[root@localhost test]# crontab [-u name] [-l|-e|-r]

-bash: -e: command not found

-bash: -r]: command not found

[-u: 没有那个文件或目录

[root@localhost test]# crontab -e

no crontab for root - using an empty one

10 20 26 11 * cp /root/yang.txt /root/test/yang1.txt  --11月26号20点10分 将yang.txt 文件拷贝到 test文件夹中并改为yang1.txt

~

"crontab.xxxx9gx37d" 1l, 53c written

crontab: installing new crontab

[root@localhost test]# crontab -l  --查看使用者当前的crontab 工作。

10 20 26 11 * cp /root/yang.txt /root/test/yang1.txt

系统设置的 /etc/crontab

[root@localhost test]# cat /etc/crontab

shell=/bin/bash  

path=/sbin:/bin:/usr/sbin:/usr/bin

<b>mailto=root 说明当crontab发生错误时或者有stderr stdout信息时,会将错误的信息传递给谁。系统设置为发送mail给root。管理员可以设置为自己的邮箱</b>

home=/

# run-parts

01 * * * * root run-parts /etc/cron.hourly --额每小时

02 4 * * * root run-parts /etc/cron.daily --每天

22 4 * * 0 root run-parts /etc/cron.weekly --每星期

42 4 1 * * root run-parts /etc/cron.monthly --每个月

现在看看刚才设置的crontab服务;

yang1.txt     -成功执行了!

当我们要删除已经设置的服务时;

[root@localhost test]# crontab -l

[root@localhost test]# crontab -r

注意:当仅仅只是删除一个任务时 请使用crontab -e 来编辑 crontab -r 是删除所有的任务。

-----------------------------------------eof------------------------------

继续阅读