[英]How to Implement Scheduled Task in Spring Web Service?
I am developing Java REST Web Service using Spring and Hibernate. 我正在使用Spring和Hibernate开发Java REST Web服务。 I need to implement a feature to schedule a future task.
我需要实现一项功能以安排将来的任务。 For example, When User Sign Up in my application I have to credit him 100 virtual credits to his account for first six months.
例如,当用户在我的应用程序中注册后,我必须在前六个月内将100个虚拟积分记入他的帐户。 Like this there is some more similar features.
像这样,还有一些类似的功能。
I am thinking like TimerTask
can be used for this feature. 我
TimerTask
可以用于此功能。 The problem is If I create Timer
for each users who sign up, I can't able to stop Timer
of specific user if he goes inactive and it seems like dumping Thread in memory. 问题是,如果我为注册的每个用户创建
Timer
,则当特定用户的Timer
变为非活动状态并且好像将线程转储到内存中时,我将无法停止该Timer
。 If 1000 users sign up there will be 1000 TimerTask
Threads. 如果有1000位用户注册,将有1000个
TimerTask
线程。
How to implement this kind of feature using Spring or Java? 如何使用Spring或Java实现这种功能? I should have the full control over the Thread, I can able to stop thread If I want.
我应该对线程具有完全控制权,如果需要的话,我可以停止线程。
you can use a Single thread to perform a task with @scheduled annotation and minimal XML configuration, I'll leave the link for your reference . 您可以使用单线程通过@scheduled注解和最少的XML配置执行任务,我将保留链接供您参考 。
you're just required to create a method in your service and place @Scheduled annotation like 您只需要在服务中创建一个方法并将@Scheduled注释放在
@Scheduled(cron = "0 15 10 15 * ?")
public void scheduleTaskUsingCronExpression(){
long now = System.currentTimeMillis() / 1000;
System.out.println("schedule tasks using cron jobs - " + now);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.