4

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


            }
}
4

1 回答 1

11

您可以使用ScheduledExecutorService2 个计划,一个用于运行任务,一个用于停止任务 - 请参见下面的简化示例:

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();
        }
    };
}
于 2012-08-03T11:12:18.443 回答