how to schedule a task at specific time?

后端 未结 1 834
不知归路
不知归路 2020-12-10 19:37

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 t

相关标签:
1条回答
  • 2020-12-10 19:45

    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();
            }
        };
    }
    
    0 讨论(0)
提交回复
热议问题