Java程序定时执行shell脚本

来源:互联网 发布:淘宝店铺怎么改类目 编辑:程序博客网 时间:2024/06/07 14:23

第一次写博客,写的不好还请见谅。

之前在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:

  1. String[] cmdScript = new String[]{"/bin/bash", "path/to/myScript.sh"};
  2. 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:

  1. 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 {@Overridepublic void run() {// TODO Auto-generated method stubString[] 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 blocke.printStackTrace();System.out.println("Error...");}        System.out.println("TimeTaskThread end!");} }


1 0
原创粉丝点击