【问题标题】:how to schedule a task at specific time?如何在特定时间安排任务?
【发布时间】:2012-08-01 10:03:24
【问题描述】:

我的 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


            }
}

【问题讨论】:

    标签: java timer scheduled-tasks scheduling


    【解决方案1】:

    您可以使用带有 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();
            }
        };
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-21
      • 2012-09-18
      • 2010-12-31
      • 2020-10-26
      • 2019-06-03
      • 2015-05-09
      • 2019-09-29
      相关资源
      最近更新 更多