您的位置:首页 > 运维架构 > Shell

Java程序定时执行shell脚本

2017-02-16 10:38 435 查看
第一次写博客,写的不好还请见谅。

之前在Linux环境中想定期执行某个脚本,第一反应就是将这个task加入到crontab里(crontab的知识点这里就不具体介绍了),当然,这种做法一般情况下是可行的。但是,当你发现,你没有编辑crontab权限,或者你所用的用户不在可执行crontab里面任务的列表时,怎么办呢?

我的解决方法是后台跑Java程序,利用Java程序定时执行shell脚本。

如何在Java代码中定时执行shell脚本?引用下面这位朋友在Quora的回答。

Terrence
Cox, Trainer at Linux Academy (http://linuxacademy.com)

There are two methods that work generally well depending on what kind of flexibility you need within your code and for the script you need to call. Here are examples:
String[] cmdScript = new String[]{"/bin/bash", "path/to/myScript.sh"};
Process procScript = Runtime.getRuntime().exec(cmdScript);

If you only need to call your script without any other parameters, that is the most direct method. Although you can add parameters directly after that name of the script if needed, complex parameters (spaces, special characters, etc) can cause formatting issues
and lead to bugs.

If you want to be able to debug easier and keep your parameters separate, you can use the ProcessBuilder class, something like:
Process procBuildScript = new ProcessBuilder("path/to/myScript.sh", "myArg1 myArg2").start();

我用的是第一种方法Runtime,下面贴上我的代码,很简单。

TimeTask.java:

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;

public class TimeTask {
Timer timer;

public Date getTime() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 1); //设置“时”为1,HOUR_OF_DAY代表24小时制
calendar.set(Calendar.MINUTE, 10); //设置“分”为10
calendar.set(Calendar.SECOND, 00); //设置“秒”为0
Date time = calendar.getTime();

return time;

}

public TimeTask(){
Date time = getTime();
System.out.println("The schedule time is:" + time);
timer = new Timer();
timer.schedule(new TimeTaskThread(), time); //创建定时执行的任务
}

public static void main(String[] args) {
new TimeTask();
}

}


TimeTaskThread:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;

public class TimeTaskThread extends TimerTask {

@Override
public void run() {
// TODO Auto-generated method stub

String[] cmdScript = new String[]{"/bin/bash", "/data/enovia_dev/sanitytest/EAICheck/EAICheck.sh"}; //脚本位置及类型
try {
Process procScript = Runtime.getRuntime().exec(cmdScript); //执行脚本
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Error...");
}

System.out.println("TimeTaskThread end!");

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java shell