我正在尝试编写一个每 3 分钟运行一次的简单 Java 程序。我正在使用 Timer 和 TimerTask 来调用这些类。
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class Receiver
{
public static void main(String[] args)
{
System.out.println("Time now is -> " + new Date());
Timer timer = new Timer();
TimerTask task = new ReceiverTask();
timer.scheduleAtFixedRate(task, 0, 180000);
}
}
class DPGReceiverTask extends TimerTask
{
private ArrayList<TaskArgs> m_tasks = new ArrayList<TaskArgs>();
public ReceiverTask()
{
m_tasks.add(new TaskArgs("com.comp.Receiver", new String[] { "ARG1", "ARG2"}));
}
public void run()
{
System.out.println("Receiver Started!");
String classpath = "D:/Receiver;D:/Receiver/lib/*";
int i = 0;
ArrayList<Process> processes = new ArrayList<Process>();
for (TaskArgs task: m_tasks)
{
try
{
List<String> command = new ArrayList<String>();
command.add(System.getProperty("java.home") + "/bin/java");
command.add("-classpath");
command.add(classpath);
command.add(task.Name);
String[] args = task.Args;
for (String arg : args)
{
command.add(arg);
}
Process process = new ProcessBuilder(command).start();
processes.add(process);
}
catch (IOException e)
{
e.printStackTrace();
}
}
try
{
for (Process process : processes)
{
int exitCode = process.waitFor();
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public class TaskArgs
{
public TaskArgs(String name, String[] args)
{
Name = name;
Args = args;
}
public String Name;
public String[] Args;
}
我实现winsw
并创建了运行 bat 文件的服务,而后者又运行 java:
接收任务.bat
java -classpath ReceiverService.jar Receiver
接收器任务.xml
<service>
<id>receiverTask</id>
<name>receiverTask</name>
<description>receiver Service</description>
<executable>receiverTask.bat</executable>
<logpath>D:\winsw\logs\Service</logpath>
<log mode="roll-by-time">
<pattern>yyyyMMdd</pattern>
</log>
<depend>Spooler</depend>
<startargument>run</startargument>
<stopargument>stop</stopargument>
</service>
我在当前的实现中遇到了两个问题:
- 无论当前java是否完成,Timer都会在3分钟后启动另一个进程。
- 停止服务(winsw - java 服务包装器)不会停止运行 java.exe 或 cmd.exe 的进程
我尝试添加销毁方法来杀死进程,但这真的是要走的路吗?
...
try
{
for (Process process : processes)
{
Timer t = new Timer();
TimerTask killer = new TimeoutProcessKiller(process);
t.schedule(killer, 178000);
int exitCode = process.waitFor();
killer.cancel();
}
}
public class TimeoutProcessKiller extends TimerTask
{
private Process p;
public TimeoutProcessKiller(Process p)
{
this.p = p;
}
public void run()
{
p.destroy();
}
}
有没有人有什么建议?