Linux crontab定时使用入门

  Linux crontab的使用还是很简单的, 主要用于定时执行任务, 在本文中, 我们来玩一下linux中的crontab, 确保任何菜鸟都能学会。

1.先写个待定时执行的shell脚本, test.sh内容如下:

#! /bin/bash 
echo "yes" >> /home/taoge/Desktop/abc.txt 

  保存好, 切记要添加该文件的可执行权限, 我一般用chmod 777 test.sh搞起。 为了便于验证, 可以手动执行以下, 确保手动执行可以成功, 如下:

taoge@localhost Desktop> cat test.sh 
#! /bin/bash 
echo "yes" >> /home/taoge/Desktop/abc.txt 
taoge@localhost Desktop> chmod 777 test.sh 
taoge@localhost Desktop> ./test.sh 
taoge@localhost Desktop> cat abc.txt 
yes

 

2.执行crontab -e命令, 相当于vim进入了“某文件”, 在其中编写定时内容, 然后用:wq保存退出, 就像vim操作一样, 简单得很。 查看某文件的内容, 可以用crontab -l, 如下:

taoge@localhost Desktop> crontab -l 
# added by taoge 
* * * * * /home/taoge/Desktop/test.sh & 

taoge@localhost Desktop> 

  如上就写好了定时任务, 至于是什么意思, 网上一所一大推, 故不详述。

  如上两部动作就可以完成定时执行test.sh的任务了, 从结果看, 每分钟abc.txt文件都会多出一行:

taoge@localhost Desktop> tail -f abc.txt 
yes 
yes 
yes

  就这么简单。 还有个问题, 如上的“某文件”到底在哪里?

taoge@localhost Desktop> cat /var/spool/cron/taoge 
cat: /var/spool/cron/taoge: Permission denied 
taoge@localhost Desktop> su 
Password: 
root@localhost Desktop> cat /var/spool/cron/taoge 
# added by taoge 
* * * * * /home/taoge/Desktop/test.sh & 

  可见, 当前用户(taoge)是无法直接访问这个文件的, 需要root才能访问。 所以, 对于普通用户taoge, 只能用crontab -e和crontab -l


附:crontab的时间设置和预期执行时间

Linux
*    *    *    *    *    *
-    -    -    -    -    -
|    |    |    |    |    |
|    |    |    |    |    + year [optional]
|    |    |    |    +----- day of week (0 - 7) (Sunday=0 or 7)
|    |    |    +---------- month (1 - 12)
|    |    +--------------- day of month (1 - 31)
|    +-------------------- hour (0 - 23)
+------------------------- min (0 - 59)

Java(Spring)
*    *    *    *    *    *    *
-    -    -    -    -    -    -
|    |    |    |    |    |    |
|    |    |    |    |    |    + year [optional]
|    |    |    |    |    +----- day of week (0 - 7) (Sunday=0 or 7)
|    |    |    |    +---------- month (1 - 12)
|    |    |    +--------------- day of month (1 - 31)
|    |    +-------------------- hour (0 - 23)
|    +------------------------- min (0 - 59)
+------------------------------ second (0 - 59)

 

文章来源:https://blog.csdn.net/stpeace/article/details/52498240

posted on 2018-06-23 16:14  bijian1013  阅读(168)  评论(0)    收藏  举报

导航