java 如何在特定时间安排任务?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11794313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to schedule a task at specific time?
提问by Mr.Cool
i have one problem with java scheduler,my actual need is i have to start my process at particular time, and i will stop at certain time ,i can start my process at specific time but i can't stop my process at certain time ,how to specify the process how long to run in scheduler,(here i will not put while ) any one have suggestion for that.
我有一个 Java 调度程序的问题,我的实际需要是我必须在特定时间启动我的进程,我会在特定时间停止,我可以在特定时间启动我的进程,但我无法在特定时间停止我的进程,如何指定进程在调度程序中运行多长时间,(这里我不会放 while )任何人对此都有建议。
import java.util.Timer;
import java.util.TimerTask;
import java.text.SimpleDateFormat;
import java.util.*;
public class Timer
{
public static void main(String[] args) throws Exception
{
Date timeToRun = new Date(System.currentTimeMillis());
System.out.println(timeToRun);
Timer timer1 = new Timer();
timer1.schedule(new TimerTask()
{
public void run()
{
//here i call another method
}
} }, timeToRun);//her i specify my start time
}
}
回答by assylias
You could use a ScheduledExecutorService
with 2 schedules, one to run the task and one to stop it - see below a simplified example:
您可以使用ScheduledExecutorService
2 个计划,一个运行任务,一个停止它 - 请参见下面的简化示例:
public static void main(String[] args) throws InterruptedException {
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
Runnable task = new Runnable() {
@Override
public void run() {
System.out.println("Starting task");
scheduler.schedule(stopTask(),500, TimeUnit.MILLISECONDS);
try {
System.out.println("Sleeping now");
Thread.sleep(Integer.MAX_VALUE);
} catch (InterruptedException ex) {
System.out.println("I've been interrupted, bye bye");
}
}
};
scheduler.scheduleAtFixedRate(task, 0, 1, TimeUnit.SECONDS); //run task every second
Thread.sleep(3000);
scheduler.shutdownNow();
}
private static Runnable stopTask() {
final Thread taskThread = Thread.currentThread();
return new Runnable() {
@Override
public void run() {
taskThread.interrupt();
}
};
}