Java 中是否有类似 cron 的 ScheduledExecutorService 实现?

发布于 2024-07-11 15:24:25 字数 229 浏览 8 评论 0原文

Java 中的 ScheduledExecutorService 对于以固定间隔或固定延迟重复任务非常方便。 我想知道是否有类似现有 ScheduledExecutorService 的东西,可以让您指定一天中的某个时间来安排任务,而不是间隔,即“我希望该任务每天上午 10 点触发”。

我知道你可以使用 Quartz 来实现这一点,但如果可能的话,我宁愿不使用该库(它是一个很棒的库,但由于某些原因我不想拥有依赖项)。

The ScheduledExecutorService in Java is pretty handy for repeating tasks with either fixed intervals or fixed delay. I was wondering if there is an something like the existing ScheduledExecutorService that lets you specify a time of day to schedule the task at, rather than an interval i.e. "I want this task to fire at 10am each day".

I know you can achieve this with Quartz, but I'd rather not use that library if possible (it's a great library but I'd rather not have the dependency for a few reasons).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

清泪尽 2024-07-18 15:24:25

ThreadPoolTask​​Scheduler,可以在不需要外部线程管理时使用。 在内部,它委托给一个 ScheduledExecutorService 实例。 ThreadPoolTask​​Scheduler 也实现了 Spring 的 TaskExecutor 接口,因此单个实​​例可用于异步执行以及计划的和可能重复的执行。

CronTrigger() 接受 cronExpression http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/support/CronSequenceGenerator.html

有关此解决方案的更多信息,请参阅 Spring 文档: https://docs.spring.io/spring /docs/current/spring-framework-reference/html/scheduling.html

import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import java.util.Date;

public class CronTriggerSpringTest{
public static void main(String args[]){
    String cronExpression = "0/5 * * * * *";
    ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.initialize();
    scheduler.schedule(new Runnable() {
        @Override
        public void run() {
            System.out.println("Hello Date:"+new Date());
        }
    }, new CronTrigger(cronExpression));
}
}

ThreadPoolTaskScheduler, can be used whenever external thread management is not a requirement. Internally, it delegates to a ScheduledExecutorService instance. ThreadPoolTaskScheduler implements Spring’s TaskExecutor interface too, so that a single instance can be used for asynchronous execution as well as scheduled, and potentially recurring, executions.

Where as CronTrigger() takes in cronExpression http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/support/CronSequenceGenerator.html

For more information on this solution refer Spring docs: https://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html

import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import java.util.Date;

public class CronTriggerSpringTest{
public static void main(String args[]){
    String cronExpression = "0/5 * * * * *";
    ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.initialize();
    scheduler.schedule(new Runnable() {
        @Override
        public void run() {
            System.out.println("Hello Date:"+new Date());
        }
    }, new CronTrigger(cronExpression));
}
}
红焚 2024-07-18 15:24:25

更多搜索发现 CronExecutorService 在 HA-JDBC 中。 有趣的是,它的 CronExpression 类,但仅此而已。 那还不错。

更新:我已经修复了损坏的链接以指向新版本,但我不知道这是否是唯一的依赖项

A bit more searching has turned up CronExecutorService in HA-JDBC. Interestingly, it has a dependency on Quartz for its CronExpression class, but that's it. That's not too bad.

Update: I've fixed the broken links to point at new versions, but I don't know if that is the only dependency any more

屋顶上的小猫咪 2024-07-18 15:24:25

您可以使用 Timer 类。 具体来说,scheduleAtFixedRate(TimerTask 任务,日期firstTime,长周期)。 您可以在其中将任务设置为在特定日期上午 10 点开始并每 24 小时重复一次。

You can use the Timer class. Specifically, scheduleAtFixedRate(TimerTask task, Date firstTime, long period). Where you can set a task to start at 10am on a particular day and repeat every 24 hours.

稳稳的幸福 2024-07-18 15:24:25

当您使用scheduleAtFixedRate 时,您提供了延迟。 因此,延迟时间可能是上午 10 点,周期为 24 小时。
即使使用计时器,这也可能会有点偏差,因此您可以做的是安排一个任务,每次将其自身添加到 ScheduledExecutorService 中并具有适当的延迟。

When you use scheduleAtFixedRate you provide a delay. So the delay can be the difference to 10 am and period is 24 hours.
This could drift a bit, even with a timer so what you can do is schedule a task which adds itself to the ScheduledExecutorService with an appropriate delay each time.

唐婉 2024-07-18 15:24:25

CronScheduler 修复了 ScheduledThreadPoolExecutor 的时钟漂移问题。用于实际按照 UTC 时间、Unix 时间或系统时间进行调度,而不是由 System.nanoTime 提供的进程内时间抽象。

CronScheduler 还提供 scheduleAtRoundTimesInDay 处理时区工作人员和夏令时更改。

Duration syncPeriod = Duration.ofMinutes(1);
CronScheduler cron = CronScheduler.create(syncPeriod);
ZoneId myTZ = ZoneId.systemDefault();
cron.scheduleAtRoundTimesInDay(Duration.ofHours(2), myTZ, runTimeMillis -> {
    // Do the task
});

There is CronScheduler which fixes the clock drift problem with ScheduledThreadPoolExecutor when the latter is employed to actually schedule in terms of UTC time, Unix time, or system time, rather than in-process abstraction of time provided by System.nanoTime.

CronScheduler also offers scheduleAtRoundTimesInDay which handles the time zone staff and daylight saving time changes.

Duration syncPeriod = Duration.ofMinutes(1);
CronScheduler cron = CronScheduler.create(syncPeriod);
ZoneId myTZ = ZoneId.systemDefault();
cron.scheduleAtRoundTimesInDay(Duration.ofHours(2), myTZ, runTimeMillis -> {
    // Do the task
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文