现在由于开发要求,需要用到定时器的地方可能比较多。在这里把使用spring定时器的基础方法分享出来,希望能给大家带来帮助。
方式一:使用配置方式
导入jar包
在spring核心配置文件中添加命名空间和xmlschema地址
xmlns:task="http://www.springframework.org/schema/task
xsi:schemaLocation="
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd"
定义一个定时器类,使用@service注解(理论上component、repository等注解都可以。和我们在service层使用@service不使用@component一样,这里建议这样使用)
import org.springframework.stereotype.Service;
/**
* 定时器
* @author huangzhilin
*
*/
@Service
public class Task {
public void task1() {
System.out.println("开始任务......");
}
}
然后在spring配置文件中配置该定时器
<!-- 配置spring自动扫描 -->
<context:component-scan base-package="com.jk"></context:component-scan>
<!-- 定时器 -->
<task:scheduled-tasks>
<!-- task 为我们的Task类,task1为计划方法,cron表达式定义计划周期 -->
<task:scheduled ref="task" method="task1" cron="0/3 * * * * ?"/>
</task:scheduled-tasks>
本地测试一下:
public class Test {
public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext("src/main/resourse/applicationContext.xml");
}
}
方式二:使用注解
同配置方式,导入jar包,添加命名空间和xmlschema地址后,spring配置文件中配置
<task:executor id="executor" pool-size="1" />
<task:scheduler id="scheduler" pool-size="10" />
<task:annotation-driven executor="executor" scheduler="scheduler" />
然后在自定义类中注解
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class TaskAnno {
@Scheduled(cron="0/3 * * * * ?")
public void task(){
System.out.println("开始任务......");
}
}
本地测试:
public class Test {
public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext("src/main/resourse/applicationContext.xml");
}
}
上面提到的cron表达式本身是一个字符串,字符串一5或6个空格隔开,分为6或7个域,都有着不同的含义。
Seconds Minutes Hours DayofMonth Month DayofWeek Year或
Seconds Minutes Hours DayofMonth Month DayofWeek
具体的编写方式可自行Google或百度。就像上面出现的 "0/3 * * * * ?"表示每3秒执行一次计划任务。下面给出一个在线cron表达式生成网页,感兴趣的可以看啊看看