ubuntu 下使用crontab定时执行java程序

题记之前使用solr进行全文检索,涉及到检索更新问题,这里采用定时更新方法,现在使用的系统为ubuntu,因此考虑crontab.解决思路

一.准备工具

打包java程序jar安装crontab

二.编写crontab 脚本

过程

一.工具准备 1,制作jar包,可以通过java jar命令,也可以通过eclipse工具. 2.安装crontab ubuntu上安装比较方便:

sudo apt-get install crontab

二.编写crontab脚本 1.认识crontab

Cron is a system daemon used to execute desired tasks (in the background) at designated times.

cron 属于一个守护进程,用来在特定的时间执行指定的任务,一般是后台运行.定义表达的很明确,使用时要确定时间和命令即可.

格式也简单:

minute (0-59), hour (0-23, 0 = midnight), day (1-31), month (1-12), weekday (0-6, 0 = Sunday), command

简单例子:

* * * * * command 表示每一分钟就执行一下command.

遇到的问题

(1)本身的java程序只是做一个测试,就是一个简单的弹出对话框,在编写crontab时候,出现没有反应的情况. 查看log—>/var/log/syslog 可以发现在日志文件中出现:No MTA installed, discarding output的问题.

根据查找资料发现crontab执行脚本时是不会直接错误的信息输出,而是会以邮件的形式发送到你的邮箱里,这时候就需要邮件服务器了,如果你没有安装邮件服务器,它就会报这个错。

通过在crontab脚本后面添加> /dev/null 2>&1,可以解决这个问题,也就是表示先将标准输出重定向到/dev/null,,然后将标准错误重定向到标准输出,由于标准输出已经重定向到了/dev/null,因此标准错误也会重定向到/dev/null.

(2)开启crontab日志

重启服务后,可还是没有出现对话框,查看日志没有错误出现,这就很奇怪了. 之后发现要启动GUI应用时候,需要启动系统的display. It is possible to run gui applications via cronjobs. This can be done by telling cron which display to use.

00 06 * * * env DISPLAY=:0 gui_appname

The env DISPLAY=:0 portion will tell cron to use the current display (desktop) for the program

可以在crontab里面设置env DISPLAY,也可以在shell程序里面添加:export DISPLAY=:0.0DISPLAY=:0 The env DISPLAY=:0 portion will tell cron to use the current display (desktop) for the program “gui_appname”.DISPLAY=:0.0 if you have multiple monitors, don’t forget to specify on which one the program is to be run. The env DISPLAY=:0.0 portion will tell cron to use the first screen of the current display for the program “gui_appname”.总结附录编写代码

crontab代码: 每分钟执行test.sh脚本

* * * * * /bin/bash /home/show_crontab/test.sh

test.sh脚本:

DISPLAY=:0.0 #启动GUI显示java -jar test.jar # 以防万一,这里的文件最好写成绝对路经

参考资料: [1] https://help.ubuntu.com/community/CronHowto [2] [3] [4] [5]

纵然走过那么多城市,对于未知的风景,还是好奇。

ubuntu 下使用crontab定时执行java程序

相关文章:

你感兴趣的文章:

标签云: