简体   繁体   English

在Spring MVC中调度任务

[英]Scheduling a Task in Spring MVC

In my Spring MVC application i need to schedule a task with specific date & Time. 在我的Spring MVC应用程序中,我需要安排具有特定日期和时间的任务。 Like- i have to schedule to send a email which will be configured dynamically by customer. 我必须安排发送一封由客户动态配置的电子邮件。 In Spring @Schedule annotation is there but how can i change value dynamically every time with any date & Time. 在Spring @Schedule中有注释,但是如何在每次使用任何日期和时间时动态更改值。

Any help is appreciated. 任何帮助表示赞赏。

You should try TaskScheduler , see the javadoc here : 您应该尝试TaskScheduler ,请在此处查看javadoc:

private TaskScheduler scheduler = new ConcurrentTaskScheduler();

@PostConstruct
private void executeJob() {
    scheduler.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            // your business here
        }
    }, INTERVAL);
}

Refer Spring Task Execution and Scheduling 参考Spring Task Execution and Scheduling

Example Annotations 示例注释

@Configuration
@EnableAsync
@EnableScheduling
public class MyComponent {

    @Async
    @Scheduled(fixedDelay=5000, repeatCount=0)
    public void doSomething() {
       // something that should execute periodically
    }
}

I think the repeatCount=0 will make the function execute only once (yet to test) 我认为repeatCount = 0会使函数只执行一次(尚未测试)

Full example with Quartz scheduler http://www.mkyong.com/spring/spring-quartz-scheduler-example/ Quartz调度程序的完整示例http://www.mkyong.com/spring/spring-quartz-scheduler-example/

You need to introduce XML configuration as follows 您需要按如下方式引入XML配置

<task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>
<task:executor id="myExecutor" pool-size="5"/>
<task:scheduler id="myScheduler" pool-size="10"/>}

You can achieve this easily within standard java API, by scheduling task for time difference between the time task is created and target date entered by customers. 您可以通过在创建时间任务和客户输入的目标日期之间的时差安排任务,在标准Java API中轻松实现此目的。 Simply provide this difference as parameter delay . 只需将此差异作为参数delay

ScheduledThreadPoolExecutor 的ScheduledThreadPoolExecutor

schedule(Callable<V> callable, long delay, TimeUnit unit)

Creates and executes a ScheduledFuture that becomes enabled after the given delay. 创建并执行在给定延迟后变为启用的ScheduledFuture。

ScheduledFuture<?>  schedule(Runnable command, long delay, TimeUnit unit)

Creates and executes a one-shot action that becomes enabled after the given delay. 创建并执行在给定延迟后启用的一次性操作。

So you either have to submit Runnable or Callable to this service. 因此,您必须向此服务提交Runnable或Callable。

You can refer to this answer for calculation between dates: 您可以参考此答案进行日期之间的计算:

time difference 时间差异

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM