java只做一次的任务,java – Spring调度任务 – 只运行一次

您可以使用Spring的TaskScheduler实现之一.我提供了一个不需要太多配置的示例(ConcurrentTaskScheduler包装一个单线程的预定执行程序).

The simplest method is the one named schedule that takes a Runnable

and Date only. That will cause the task to run once after the

specified time. All of the other methods are capable of scheduling

tasks to run repeatedly.

简单的工作实例:

private TaskScheduler scheduler;

Runnable exampleRunnable = new Runnable(){

@Override

public void run() {

System.out.println("Works");

}

};

@Async

public void executeTaskT() {

ScheduledExecutorService localExecutor = Executors.newSingleThreadScheduledExecutor();

scheduler = new ConcurrentTaskScheduler(localExecutor);

scheduler.schedule(exampleRunnable,

new Date(1432152000000L));//today at 8 pm UTC - replace it with any timestamp in miliseconds to text

}

...

executeTaskT() //call it somewhere after the spring application has been configured

注意:

To enable support for @Scheduled and @Async annotations add

@EnableScheduling and @EnableAsync to one of your @Configuration

classes

更新 – 取消计划的任务

TaskScheduler的schedule方法返回一个ScheduledFuture,它是一个可以取消的延迟结果的动作.

所以为了取消它,你需要保留一个句柄到计划的任务(即保留ScheduledFuture返回对象).

更改以上代码以取消任务:

>在您的executeTaskT方法之外声明ScheduledFuture.

私人计划

>修改您的调用以调度以保持返回对象:

scheduledFuture = scheduler.schedule(exampleRunnable,

新日期(1432152000000L));

>在您的代码中某个地方的scheduledFuture对象上调用取消

boolean mayInterruptIfRunning = true;scheduledFuture.cancel(mayInterruptIfRunning);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值