Scheduling periodic tasks and clock drift

前端 未结 3 472
耶瑟儿~
耶瑟儿~ 2021-01-23 01:09

I would like to schedule a periodic task which executes every X hours. I have a service which is written in Java and I was thinking of creating a long running background thread

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-23 01:29

    Is clock drift on my host an issue I should be worried about?

    Yes, clock drift can be an issue when using ScheduledThreadPoolExecutor.

    CronScheduler is specifically designed to be proof against clock drift.

    Example usage:

    Duration syncPeriod = Duration.ofMinutes(1);
    CronScheduler cron = CronScheduler.create(syncPeriod);
    
    // If you need just precisely "once every X hours", irrespective of the
    // starting time
    cron.scheduleAtFixedRate(0, X, TimeUnit.HOURS, runTimeMillis -> {
        // Do the task
    });
    
    // If you need "once every X hours" in terms of wall clock time,
    // in some time zone:
    ZoneId myTZ = ZoneId.systemDefault();
    cron.scheduleAtRoundTimesInDay(Duration.ofHours(X), myTZ, runTimeMillis -> {
        // Do the task
    });
    

    See Javadocs for scheduleAtRoundTimesInDay.

提交回复
热议问题