how to schedule a task at specific time?

两盒软妹~` 提交于 2019-11-28 11:42:27

You could use a ScheduledExecutorService with 2 schedules, one to run the task and one to stop it - see below a simplified example:

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();
        }
    };
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!