四时宝库

程序员的知识宝库

Linux使用crontab定时执行shell脚本

一、首先我们先看一下是否安装了crontab。一般情况下Linux系统会自带crontab及crond。如果没有安装,请使用以下指令安装:

Bash
yum install vixie-cron      
yum install crontabs

二、 然后我们写一个名字叫做test.sh的shell脚本。很简单,就是输出一段字符。

Bash
[root@centos8 crontab]# vim test.sh
[root@centos8 crontab]# cat test.sh
#!/bin/bash
echo "hello world!"

# 我们的目的是每分钟执行一次这个shell脚本,所以要再建立一个存放日志的log文件,然后给予test.sh权限。
[root@centos8 crontab]# touch log
[root@centos8 crontab]# ls
log  test.sh
[root@centos8 crontab]# chmod +x test.sh

三、然后我们就要使用crontab了,首先进入它的配置文件,在/etc/crontab 中添加我们的调度命令。

Bash
[root@centos8 crontab]# vim /etc/crontab
[root@centos8 crontab]# cat /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed
* * * * * root /opt/crontab/test.sh >> /opt/crontab/log

# root表示以root用户身份来运行 >>表示运行脚本后重定向到log文件中

CentOS7上的cron命令

Bash
systemctl start crond.service  //启动服务
systemctl stop crond.service  //关闭服务
systemctl restart crond.service  //重启服务
systemctl reload crond.service  //重新载入配置
systemctl status crond.service   //查看状态

# 或者
crond start
crond stop
crond restart
crond reload
crond status

# 查看crontab的日志
日志文件为/var/log/cron
cat /var/log/cron

java启动的脚本crontab定时任务启动失败原因

Bash
# crontab定时任务启动脚本失败原因:

1.首先手动执行脚本,查看是否能启动

2.如果启动失败,脚本写错,如果启动成功,那有概率是java环境变量问题

在脚本第一行添加
source /etc/profile
每次执行重新加载java环境变量

文件路径填完整!

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接