LinuxGem
此处为老的 LinuxGem,新版 LinuxGem 请移步 www.linuxgem.org

用 cron 定时执行任务

galeki posted @ 2008年3月03日 05:27 in Bash 和它的朋友们 with tags cron crontab , 14419 阅读

假如你有一些任务要定期执行,比如清理磁盘、删除过期文件、发送邮件和提醒,这个时候可以用 cron 来帮你。

首先是安装,大多数发行版都预装了,Gentoo下的cron有许多种实现,可以用 emerge --search cron 来查看,这里用 vixie-cron,因为功能比较完整,命令语法也比较通用。

# emerge vixie-cron

之后要启动 cron 服务:

# /etc/init.d/vixie-cron start

别忘了把 cron 加入到启动脚本中:

# rc-update add vixie-cron default

完成安装。

系统cron设定:/etc/crontab

通过 /etc/crontab 文件,可以设定系统定期执行的任务,当然,要想编辑这个文件,得有root权限。

让我们打开 /etc/crontab,看看cron的语法:

  1. # for vixie cron
  2. #
  3. # $Header: /var/cvsroot/gentoo-x86/sys-process/vixie-cron/files/crontab-3.0.1-r4,v 1.1 2005/03/04 23:59:48 ciaranm Exp $
  4. #
  5. #
  6.  
  7. # Global variables
  8. SHELL=/bin/bash
  9. PATH=/sbin:/bin:/usr/sbin:/usr/bin
  10. MAILTO=root
  11. HOME=/
  12.  
  13. # check scripts in cron.hourly, cron.daily, cron.weekly and cron.monthly
  14. 0  *  * * *     root    rm -f /var/spool/cron/lastrun/cron.hourly
  15. 1  3  * * *     root    rm -f /var/spool/cron/lastrun/cron.daily
  16. 15 4  * * 6     root    rm -f /var/spool/cron/lastrun/cron.weekly
  17. 30 5  1 * *     root    rm -f /var/spool/cron/lastrun/cron.monthly
  18. */10  *  * * *  root    test -x /usr/sbin/run-crons && /usr/sbin/run-crons 

以上是一个默认的/etc/crontab文件,7~11行设定了执行任务时特定环境变量的值,MAILTO=root 指出出错信息发给root。

真正描述执行的任务在 14~18 行,每行代表了一个定期执行的任务,从前到后,分为3部分:

第一部分,一堆奇怪的数字和星号,这部分描述任务的执行周期和时间,后面我们将详细解释。

第二部分,上面的文件全部是 "root",描述了执行任务时的用户。

第三部分,为需要执行的完整命令。

第一部分分为5个小部分,没部分可以是数字或者星号,分别代表了分钟、小时、日期、月份、周,让我们来看一个例子:

0   7   *    *   *    root    mpg123 ~/wakeup.mp3
分 时 日 月 周

星号,即代表不限制,上面的例子就是:每天的7点0分,都将执行mpg123 ~/wakeup.mp3,放首歌,把自己从睡梦中叫醒~

以下是各部分的取之范围:

 分钟 0~59
 小时 0~23
 日期 1~31
 月份 1~12
0~6

其中周的范围0~6,0代表星期天,1~6代表周一~周六。

让我们来看更多的例子:

0  4  * * 0     root    emerge --sync && emerge -uD world              #每周日凌晨4点,更新系统
0  2  1 * *     root    rm -f /tmp/*                                                    #每月1号凌晨2点,清理/tmp下的文件
0  8  6  5 *   root     mail  robin < /home/galeki/happy.txt             #每年56日给robin发信祝他生日快乐

假如,我想每隔2分钟就要执行某个命令,或者我想在每天的6点、12点、18点执行命令,诸如此类的周期,可以通过 “ / ” 和 “ , ” 来设置:

*/2   *   *   *   *           root      ...............      #每两分钟就执行........
0  6,12,18   *   *   *    root      ...............      #每天6点、12点、18点执行........

用户的cron: crontab命令

上面我们提到的 /etc/crontab 文件,只能指定系统定期执行的命令,如果用户想设定自己定期需要执行的命令的话,就要用到crontab命令,编辑自己的crontab文件。

首先,用户必须隶属于cron组才可以用crontab命令,可以用下面的命令把用户加入到cron组中:

# gpasswd -a galeki cron

crontab命令主要有3个参数:

-e : 编辑用户的crontab。

-l  : 列出用户的crontab的内容。

-r  : 删除用户的crontab的内容。

执行crontab -e,将自动打开编辑器,你可以编辑自己的crontab文件,语法和 /etc/crontab 文件一样,不同的只是,不必再指出执行的用户,编辑后保存即可。

crontab -l用来查看自己的crontab文件内能,crontab -r删除自己的crontab。

  • 无匹配
forex market 说:
2023年8月16日 17:33

I was recommended this website by way of my cousin. I’m no longer positive whether this put up is written by means of him as no one else recognize such distinct about my difficulty. You’re amazing! Thank you! curtains dog friendly

forex market 说:
2023年8月21日 00:36

Oh my goodness! an excellent write-up dude. Thanks a ton Even so We’re experiencing problem with ur rss . Do not know why Cannot sign up for it. Is there any person obtaining identical rss dilemma? Anyone who knows kindly respond. Thnkx UFABETแทงบอลบนมือถือ

haider 说:
2023年8月21日 19:03

You will discover obviously quite a lot of details like that to take into consideration. That´s a great point to bring up. I will offer you the thoughts above as general inspiration but clearly you will discover questions like the one you bring up where the most important factor definitely will be working in honest very good faith. I don´t know if greatest practices have emerged around things like that, but I am certain that your job is clearly identified as a fair game. แทงใบเหลืองใบแดงUFABET

forex market 说:
2023年8月22日 00:18

I am really impressed with your writing skills well with the layout for your weblog. Is that this a paid subject matter or did you modify it your self? Anyway stay up the nice high quality writing, it is rare to see a nice weblog like this one these days. UFABETแทงบอลทายผลผู้ชนะ

forex market 说:
2023年8月23日 22:43

Howdy are using WordPress for your blog platform? I’m new to the blog world but I’m trying to get started and set up my own. Do you require any html coding expertise to make your own blog? Any help would be really appreciated! 안전놀이터

haider 说:
2023年8月23日 23:06

This article contains great original thinking. The informational content here proves that things aren’t so black and white. I feel smarter from just reading this. เว็บพนันบอลออนไลน์อันดับ1

forex market 说:
2023年8月24日 19:12

Pretty nice post. I just stumbled upon your blog and wished to say that I’ve truly enjoyed browsing your blog posts. After all I will be subscribing to your feed and I hope you write again soon! UFABET เว็บพนันแตกง่าย

haider 说:
2023年8月24日 19:23

Along with every little thing that appears to be building within this particular area, many of your opinions are generally fairly radical. Nevertheless, I am sorry, but I do not subscribe to your whole strategy, all be it radical none the less. It looks to everyone that your remarks are generally not completely rationalized and in simple fact you are your self not even entirely convinced of the argument. In any case I did enjoy looking at it. เว็บบอลออนไลน์UFA

haider 说:
2023年8月25日 14:07

It is very rare these days to find sites that provide information someone is watching for. I am glad to see that your site share valued information that can help to many readers. nice one and keep writing! สมัครแทงบอลฟรี

forex market 说:
2023年8月25日 15:03

Hello! I simply would choose to offer a huge thumbs up for your great information you could have here for this post. I will be coming back to your website for much more soon. เว็บไซต์แทงบอลอันดับ1

forex market 说:
2023年8月26日 13:47

This internet site can be a walk-through like the info you wished relating to this and didn’t know who need to. Glimpse here, and you’ll certainly discover it. เว็บพนันออนไลน์UFA

haider 说:
2023年8月27日 18:44

Youre so cool! I dont suppose Ive read anything in this way just before. So nice to uncover somebody by original ideas on this subject. realy thank you for beginning this up. this site are some things that is required on-line, someone after some originality. useful problem for bringing a new challenge to the web! 메이저사이트

haider 说:
2023年8月30日 17:26

Read the full written content. There is certainly several definitely helpful details here. thankyou. “Much speech is one thing, well-timed speech is another.” by Sophocles.. 메이저사이트

haider 说:
2023年9月04日 14:05

There couple of intriguing points soon enough in this article but I do not know if I see every one of them center to heart. There exists some validity but I will take hold opinion until I investigate it further. Good write-up , thanks therefore we want far more! Included in FeedBurner likewise 안전놀이터

forex market 说:
2023年9月05日 13:55

An intriguing discussion might be priced at comment. I think that you need to write regarding this topic, it might not become a taboo subject but normally individuals are insufficient to speak on such topics. An additional. Cheers salingsilang

sdsds 说:
2023年9月08日 22:59

You created some decent points there. I looked online for any problem and discovered most individuals go in conjunction with together with your internet site. custom tactical hawaiian shirt

haider 说:
2023年9月08日 23:33

Fantastic piece of content! Take into consideration was pleased with the actual checking. I’m hoping you just read a bit more of you. I know you’ve gotten really good comprehension coupled with plans. Quite possibly very highly delighted utilizing this facts. filmyzilla 2023

haider 说:
2023年9月13日 23:28

Conexion hot new Latin Hip Hop single from Nieto. Produced y Super Producer DJ Solar. Hot track that plugs the gap in Underground Hip Hop and Latin Hip Hop! Mexican Hip Hop

haider 说:
2023年9月14日 21:54

There are some interesting points with time in this article but I do not know if I see every one of them center to heart. There is some validity but I most certainly will take hold opinion until I check into it further. Very good post , thanks and now we want a lot more! Included with FeedBurner as well สล็อต

haider 说:
2023年9月20日 14:11

Can I just say what a relief to seek out someone who actually is aware of what theyre talking about on the internet. You undoubtedly know the way to bring an issue to light and make it important. More folks have to read this and understand this aspect of croc birthday

jmaes 说:
2023年9月24日 14:37

Nice post. I discover some thing tougher on distinct blogs everyday. It will always be stimulating to read content from other writers and employ something there. I’d would prefer to apply certain with the content on my own weblog whether you don’t mind. Natually I’ll provide a link on your internet weblog. Appreciate your sharing. shillong teer common number

jmaes 说:
2023年10月02日 23:58

I’d need to talk with you here. Which isn’t something I usually do! I quite like reading a post that should get people to believe. Also, appreciate your permitting me to comment! Kalaastar song lyrics

ds 说:
2023年10月12日 19:26

After i obtained on your blog although placing interest merely slightly little bit submits. Enjoyable technique for long term, I'll be book-marking at any given time obtain types complete comes upward. Gutter Cleaning Poole

ds 说:
2023年10月21日 14:27

I have been gone for some time, but now I remember why I used to love this web site. Thanks, I will try and check back more often. How often do you update your web site? แทงบอลเงินสด

james 说:
2023年11月03日 23:57

This type of is apparently absolutely outstanding. These kinds of tiny fact is made making use of wide variety regarding certification know-how. My partner and i favour the theory much. https://sky888.win/

james 说:
2023年11月08日 01:25

I wanted to put you one very little word just to say thank you over again over the spectacular ideas you’ve provided at this time. It was certainly surprisingly open-handed of people like you to present freely all many individuals would’ve sold for an e-book to help with making some cash for themselves, specifically seeing that you might have tried it in case you wanted. These concepts as well acted to be a great way to realize that most people have similar dream the same as my very own to learn somewhat more in regard to this matter. I am sure there are some more enjoyable opportunities ahead for individuals who read carefully your blog post. digitalglobaltimes.com

WonderWrks 说:
2023年11月09日 19:12

That is furthermore a good submit that i actually appreciated studying. It isn't each day that we hold the chance to find out one thing. https://hb88a.win/

marble polishing in 说:
2023年11月13日 23:10

This excellent looks absolutely appropriate. Every one of moderate information are ready by using large number associated with encounter useful understanding. I am eager this once again greatly. https://www.salt-shaq.com


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter