解决cron 脚本的不能运行的方法:脚本中统统使用全路径

29 篇文章 0 订阅
1 篇文章 0 订阅

解决cron 脚本的不能运行的方法:脚本中统统使用全路径;

 

尤其是脚本,嵌套脚本的形式,很容易造成脚本不能运行;

1. 保证cron脚本,中命令使用全路径;

 2. 命令脚本中路径使用全路径;

3. 在命令脚本,开始处输出信息到log文件用于测试;

     如果log文件中有要输出的信息;说明cron脚本是正确的, 问题出在命令脚本,调试命令脚本;

    否则, cron脚本有问题,调试cron脚本的格式,直至log中有日志信息输出;



参考资料:http://www.cyberciti.biz/faq/how-do-i-add-jobs-to-cron-under-linux-or-unix-oses/

HowTo: Add Jobs To cron Under Linux or UNIX?

by NIX CRAFT on APRIL 16, 2006 · 195 COMMENTS· LAST UPDATED JANUARY 21, 2014

in COMMANDSLINUXUNIX

How do I add cron job under Linux or UNIX like operating system?

Cron job are used to schedule commands to be executed periodically. You can setup commands or scripts, which will repeatedly run at a set time. Cron is one of the most useful tool in Linux or UNIX like operating systems. The cron service (daemon) runs in the background and constantly checks the  /etc/crontab file, and  /etc/cron.*/ directories. It also checks the  /var/spool/cron/ directory.

crontab command

Tutorial details  
Difficulty Intermediate (rss)
Root privileges Yes
Requirements crond
Estimated completion time 20m
crontab is the command used to install, deinstall or list the tables (cron configuration file) used to drive the  cron(8) daemon in Vixie Cron. Each user can have their own crontab file, and though these are files in /var/spool/cron/crontabs, they are not intended to be edited directly. You need to use crontab command for editing or setting up your own cron jobs.

Types of cron configuration files

There are different types of configuration files:

  1. The UNIX / Linux system crontab : Usually, used by system services and critical jobs that requires root like privileges. The sixth field (see below for field description) is the name of a user for the command to run as. This gives the system crontab the ability to run commands as any user.
  2. The user crontabs: User can install their own cron jobs using the crontab command. The sixth field is the command to run, and all commands run as the user who created the crontab

Note: This faq features cron implementations written by Paul Vixie and included in many Linux distributions and Unix like systems such as in the popular 4th BSD edition. The syntax is compatible with various implementations of crond.

How Do I install or create or edit my own cron jobs?

To edit your crontab file, type the following command at the UNIX / Linux shell prompt:
$ crontab -e

Syntax of crontab (field description)

The syntax is:

 
1 2 3 4 5 /path/to/command arg1 arg2
 

OR

 
1 2 3 4 5 /root/backup.sh
 

Where,

  • 1: Minute (0-59)
  • 2: Hours (0-23)
  • 3: Day (0-31)
  • 4: Month (0-12 [12 == December])
  • 5: Day of the week(0-7 [7 or 0 == sunday])
  • /path/to/command - Script or command name to schedule

Easy to remember format:

* * * * * command to be executed
- - - - -
| | | | |
| | | | ----- Day of week (0 - 7) (Sunday=0 or 7)
| | | ------- Month (1 - 12)
| | --------- Day of month (1 - 31)
| ----------- Hour (0 - 23)
------------- Minute (0 - 59)

Your cron job looks as follows for system jobs:

1 2 3 4 5 USERNAME /path/to/command arg1 arg2

OR

1 2 3 4 5 USERNAME /path/to/script.sh

Example: Run backup cron job script

If you wished to have a script named /root/backup.sh run every day at 3am, your crontab entry would look like as follows. First, install your cronjob by running the following command:
# crontab -e
Append the following entry:
0 3 * * * /root/backup.sh
Save and close the file.

More examples

To run /path/to/command five minutes after midnight, every day, enter:
5 0 * * * /path/to/command
Run /path/to/script.sh at 2:15pm on the first of every month, enter:
15 14 1 * * /path/to/script.sh
Run /scripts/phpscript.php at 10 pm on weekdays, enter:
0 22 * * 1-5 /scripts/phpscript.php
Run /root/scripts/perl/perlscript.pl at 23 minutes after midnight, 2am, 4am ..., everyday, enter:
23 0-23/2 * * * /root/scripts/perl/perlscript.pl
Run /path/to/unixcommand at 5 after 4 every Sunday, enter:
5 4 * * sun /path/to/unixcommand

How do I use operators?

An operator allows you to specifying multiple values in a field. There are three operators:

  1. The asterisk (*: This operator specifies all possible values for a field. For example, an asterisk in the hour time field would be equivalent to every hour or an asterisk in the month field would be equivalent to every month.
  2. The comma (,) : This operator specifies a list of values, for example: "1,5,10,15,20, 25".
  3. The dash (-) : This operator specifies a range of values, for example: "5-15" days , which is equivalent to typing "5,6,7,8,9,....,13,14,15" using the comma operator.
  4. The separator (/) : This operator specifies a step value, for example: "0-23/" can be used in the hours field to specify command execution every other hour. Steps are also permitted after an asterisk, so if you want to say every two hours, just use */2.

How do I disable email output?

By default the output of a command or a script (if any produced), will be email to your local email account. To stop receiving email output from crontab you need to append >/dev/null 2>&1. For example:
0 3 * * * /root/backup.sh >/dev/null 2>&1
To mail output to particular email account let us say vivek@nixcraft.in you need to define MAILTO variable as follows:
MAILTO="vivek@nixcraft.in"
0 3 * * * /root/backup.sh >/dev/null 2>&1

See "Disable The Mail Alert By Crontab Command" for more information.

Task: List all your cron jobs

Type the following command:
# crontab -l
# crontab -u username -l

To remove or erase all crontab jobs use the following command:
# Delete the current cron jobs #
crontab -r

## Delete job for specific user. Must be run as root user ##
crontab -r -u username

Use special string to save time

Instead of the first five fields, you can use any one of eight special strings. It will not just save your time but it will improve readability.

Special stringMeaning
@rebootRun once, at startup.
@yearlyRun once a year, "0 0 1 1 *".
@annually(same as @yearly)
@monthlyRun once a month, "0 0 1 * *".
@weeklyRun once a week, "0 0 * * 0".
@dailyRun once a day, "0 0 * * *".
@midnight(same as @daily)
@hourlyRun once an hour, "0 * * * *".

Examples

Run ntpdate command every hour:
@hourly /path/to/ntpdate
Make a backup everyday:
@daily /path/to/backup/script.sh

More about /etc/crontab file and /etc/cron.d/* directories

/etc/crontab is system crontabs file. Usually only used by root user or daemons to configure system wide jobs. All individual user must must use crontab command to install and edit their jobs as described above. /var/spool/cron/ or /var/cron/tabs/ is directory for personal user crontab files. It must be backup with users home directory.

Understanding Default /etc/crontab

Typical /etc/crontab file entries:

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
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

First, the environment must be defined. If the shell line is omitted, cron will use the default, which is sh. If the PATH variable is omitted, no default will be used and file locations will need to be absolute. If HOME is omitted, cron will use the invoking users home directory.

Additionally, cron reads the files in /etc/cron.d/ directory. Usually system daemon such as sa-update or sysstat places their cronjob here. As a root user or superuser you can use following directories to configure cron jobs. You can directly drop your scripts here. The run-parts command run scripts or programs in a directory via /etc/crontab file:

DirectoryDescription
/etc/cron.d/Put all scripts here and call them from /etc/crontab file.
/etc/cron.daily/Run all scripts once a day
/etc/cron.hourly/Run all scripts once an hour
/etc/cron.monthly/Run all scripts once a month
/etc/cron.weekly/Run all scripts once a week

How do I use above directories to put my own scripts or jobs?

Here is a sample shell script called clean.cache. This script is created to clean up cached files every 10 days. This script is directly created at /etc/cron.daliy/ directory. In other words create a text file called /etc/cron.daily/clean.cache as follows.

 #!/bin/bash
# A sample shell script to clean cached file from lighttpd web server
CROOT="/tmp/cachelighttpd/"
 
# Clean files every $DAYS
DAYS=10
 
# Web server username and group name
LUSER="lighttpd"
LGROUP="lighttpd"
 
# Okay, let us start cleaning as per $DAYS
/usr/bin/find ${CROOT} -type f -mtime +${DAYS} | xargs -r /bin/rm
 
# Failsafe 
# if directory deleted by some other script just get it back 
if [ ! -d $CROOT ]
then
        /bin/mkdir -p $CROOT
        /bin/chown ${LUSER}:${LGROUP} ${CROOT}
fi

Save and close the file. Set the permissions:
# chmod +x /etc/cron.daily/clean.cache

How do I backup installed cron jobs entries?

Simply type the following command to backup your cronjobs to a nas server mounted at /nas01/backup/cron/users.root.bakup directory:
# crontab -l > /nas01/backup/cron/users.root.bakup
# crontab -u userName -l > /nas01/backup/cron/users.userName.bakup

SEE ALSO

http://www.xshell.net/linux/crontab-3.html

crontab不执行的原因解析

Posted by  破冰 on 2013-8-25 13:40 Sunday

1.Cron的启动与关闭

由于Cron是Linux的内置服务,可以用以下的方法启动.关闭这个服务:

/sbin/service crond start           //启动服务
/sbin/service crond stop            //关闭服务
/sbin/service crond restart        //重启服务
/sbin/service crond reload         //重新载入配置

2.Cron配置文件

2.1全局配置文件

crontab在/etc目录下面存在cron.hourly,cron.daily,cron.weekly,cron.monthly,cron.d五个目录和crontab,cron.deny二个文件.

cron.daily是每天执行一次的job,cron.weekly是每个星期执行一次的job.cron.monthly是每月执行一次的job,cron.hourly是每个小时执行一次的job.cron.d是系统自动定期需要做的任务,但是又不是按小时,按天,按星期,按月来执行的,那么就放在这个目录下面.

/etc/crontab文件一般如下:

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

我们可在此文件中添加自己需要的cron job.

/etc/cron.deny文件就是用于控制不让哪些用户使用Crontab的功能.

2.2用户配置文件

每个用户都有自己的cron配置文件,通过crontab -e 就可以编辑,一般情况下我们编辑好用户的cron配置文件保存退出后,系统会自动就存放于/var/spool/cron/目录中,文件以用户名命名.

linux的cron服务是每隔一分钟去读取一次/var/spool/cron,/etc/crontab,/etc/cron.d下面所有的内容.

3.Cron命令格式

crontab [ -u user ] 文件 
crontab [ -u user ] { -l | -r | -e }

-u:指定某一用户

-e:执行文字编辑器来设定用户(当前用户或指定用户)时程表,内定的文字编辑器是vi.
-r:删除用户时程表.
-l:列出用户时程表.

4.Cron文件格式

*  *  *  *  *  command
分 时 日 月 周   命令

第1列表示分钟1~59, 每分钟用*或者 */1表示
第2列表示小时1~23(0表示0点)
第3列表示日期1~31
第4列表示月份1~12
第5列标识号星期0~6(0表示星期天)
第6列要运行的命令

5.Cron文件使用说明

5.1 一般情况

当f1 为 * 时表示每分钟都要执行 program,f2 为 * 时表示每小时都要执行程序,其余类推. 

* * * * * /bin/usershell  每天每分钟执行一次/bin/usershell
当f1 为 a-b 时表示从第 a 分钟到第 b 分钟这段时间内要执行,f2 为 a-b 时表示从第 a 到第 b 小时都要执行,其余类推.

0-12 * * * * /bin/usershell  每天每小时从0到12分钟每分钟执行一次/bin/usershell
当f1 为 */n 时表示每 n 分钟个时间间隔执行一次,f2 为 */n 表示每 n 小时个时间间隔执行一次,其余类推.

* */2 * * * /bin/usershell  每天每2小时执行一次/bin/usershell
当f1 为 a, b, c,... 时表示第 a, b, c,... 分钟要执行,f2 为 a, b, c,... 时表示第 a, b, c...个小时要执行,其余类推.

* 1,3,5,7 * * * /bin/usershell  每天每逢1,3,4,7点执行一次/bin/usershell

5.2. 冲突逻辑

日期可以用月限定,也可以用“星期”指定,如果两个段有冲突,那么,第六段的命令将在匹配任何一个的情况下都运行,比如

"30 4 1,15 * 5",将在每月的1号和15号加每个周五,上午4:30运行.

5.3. 符号"%"

"%"在Cron文件中,有"结束命令行","换行","重定向"的作用,假如不需要"%"的特殊作用,需要使用转义符转义.

5.4. @reboot

这个不需要理解,为了达到在开机后运行,且只运行一次的目的.除了这个,也无法通过前五段的设置来实现.

@annually也是这个功能.

至于@yearly,@monthly等等其实都可以用上面的五段来设置.

 

然后我自己写了一个小例子做了下测试:

使用crontab -e进行编辑,内容为:

*/2 * * * * echo "i am crontab" >> /home/zhang/hello

这样隔两分钟就会往hello这个文件里写i am crontab


我自己写了一个脚本task.sh,直接运行task.sh时可以运行,可是加到crontab里就有运行了,后来我查看了网上的解决方法,终于解决了,先来看一下我原来写的task.sh脚本吧:

#!/bin/sh

java -jar offergateway.biz.offer-1.0-SNAPSHOT.jar


crontab定时任务的写法为:

* * * * *  /task.sh


后来我查了网上说要运行crontab,必须使用绝对路径,然后我把路径都改成绝对路径了。

在crontab的执行环境变量中,没有相应用户设置的环境变量,你需要手动设置一下环境变量,才能让它生效。于是我把上面的脚本改成:

#!/bin/sh

. /etc/profile

java -jar /home/zhang/offergateway.biz.offer-1.0-SNAPSHOT.jar


crontab也改成绝对路径:

* * * * *  sh /home/zhang/task.sh

哈哈,成功了~~happy~~


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值