网上看到好多关于定时任务的讲解,以前只简单使用过注解方式,今天项目中看到基于配置的方式实现定时任务,自己做个总结,作为备忘录吧。
基于注解方式的定时任务
首先spring-mvc.xml的配置文件中添加约束文件
xmlns:task="http://www.springframework.org/schema/task" http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd
其次需要配置注解驱动
<task:annotation-driven />
添加你添加注解的扫描包
<context:component-scan base-package="com.xxx.xxx" />
最后贴上定时任务包代码
package com.xxx.xxx; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class xxxTask { @Scheduled(cron = "0/5 * * * * ? ") // 间隔5秒执行 public void xxx() { System.out.println("----定时任务开始执行-----"); //执行具体业务逻辑---------- System.out.println("----定时任务执行结束-----"); } }
基于配置的定时任务调度框架Quartz
引入依赖
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.3</version>
</dependency>
定义一个类,方法可以写多个为需要定时执行的任务
public class AdminJob { public void job1() { System.out.pringln("执行了任务---"); } }
在spring.xml配置中添加
<bean />
<!--此处id值为需要执行的定时任务方法名-->
<bean >
<property name="targetObject" ref="adminJob"/>
<property name="targetMethod" value="job1"/>
</bean>
<!--此处为定时任务触发器-->
<bean >
<property name="jobDetail">
<ref bean="job1"/>
</property>
<property name="cronExpression">
<value>0 15 0 16 * ?</value>
</property>
</bean>
<bean >
<property name="triggers">
<list>
<ref bean="job1Trigger"/>
</list>
</property>
<property name="taskExecutor" ref="executor"/>
</bean>
<bean >
<property name="corePoolSize" value="10"/>
<property name="maxPoolSize" value="100"/>
<property name="queueCapacity" value="500"/>
</bean>
最后还有一种普通java的定时任务代码 基于线程池的方式实现定时任务
import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class Task3 { public static void main(String[] args) { Runnable runnable = new Runnable() { public void run() { // task to run goes here System.out.println("Hello !!"); } }; ScheduledExecutorService service = Executors .newSingleThreadScheduledExecutor(); service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS); } }