Spring Scheduled实现定时任务

时间:2022-09-02 02:20:31

1 在.xml配置文件中引入命名空间

xmlns:task="http://www.springframework.org/schema/task" 
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd"

2 设置自动发现

<task:annotation-driven/> 

3 在需要定时执行的方法上加上@Scheduled注解,一个实例如下:

@Service
public class AreaCacheService implements InitializingBean {

Ehcache areaCache;

@Override
public void afterPropertiesSet() throws Exception {
refresh();
}

@Scheduled(fixedDelay = 1000, initialDelay = 1000)
public void refresh() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
System.out.println(sdf.format(new Date()) + ": refresh cache...");
}
}

以上例子让方法每次执行后都间隔一秒继续执行,执行结果如下:

20160820 17:54:47: refresh cache…
20160820 17:54:48: refresh cache…
20160820 17:54:49: refresh cache…
20160820 17:54:50: refresh cache…
20160820 17:54:51: refresh cache…
20160820 17:54:52: refresh cache…

注意:

Exactly one of the ‘cron’, ‘fixedDelay(String)’, or ‘fixedRate(String)’ attributes is required
(cron, fixdDelay, fixedRate三个属性必须设置一个)

属性含义:

属性 解释
cron A cron-like expression, extending the usual UN*X definition to include triggers on the second as well as minute, hour, day of month, month and day of week.
fixedDelay Execute the annotated method with a fixed period in milliseconds between the end of the last invocation and the start of the next.
fixedDelayString Execute the annotated method with a fixed period in milliseconds between the end of the last invocation and the start of the next.
fixedRate Execute the annotated method with a fixed period in milliseconds between invocations.
fixedRateString Execute the annotated method with a fixed period in milliseconds between invocations.
initialDelay Number of milliseconds to delay before the first execution of a fixedRate() or fixedDelay() task.
initialDelayString Number of milliseconds to delay before the first execution of a fixedRate() or fixedDelay() task.
zone A time zone for which the cron expression will be resolved.

也可以用配置文件来配置定时任务:

 <task:scheduled-tasks>   
<task:scheduled ref="taskJob" method="job1" cron="0 * * * * ?"/>
</task:scheduled-tasks>

其中taskJob是对应的javaBean,job1是要定时执行的方法。