如何在特定时间安排任务?

时间:2012-08-03 10:53:44

标签: java timer scheduled-tasks scheduling

我有一个java调度程序的问题,我的实际需要是我必须在特定时间启动我的进程,我会在某个时间停止,我可以在特定时间启动我的进程但我无法阻止我的进程某些时候,如何指定进程在调度程序中运行多长时间(这里我不会放入),任何人都有建议。

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


            }
}

1 个答案:

答案 0 :(得分:10)

您可以使用带有2个时间表的ScheduledExecutorService,一个用于运行任务,另一个用于停止任务 - 请参阅下面的简化示例:

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();
        }
    };
}