定时任务分为周期性执行(一小时运行一次,一分钟运行一次)和某个时间点(几点几刻)执行
<dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.2</version> </dependency>
然后在spring-servlet.xml中找个地方加上
xmlns:task="http://www.springframework.org/schema/task"
和
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
然后配置一下bean,随便起个名字,比如叫做quartzTaskBean,然后配置任务时间表
任务时间表需要引用这个bean的id就是刚才配置的quartzTaskBean
定时任务按道理应该属于service吧。。。所以在com.hs.service中创建一个服务,叫做QuartzTaskService,所有的定时任务都写在这里好了
何时执行用
cron="* * * * * ?"配置,五个星星分别是 秒 分 时 日 月 ❓是周,后边还可以继续添加年这个东西自己算太麻烦了,网上有工具
cron计算工具
<task:scheduled-tasks> <task:scheduled ref="quartzTaskBean" method="quartzJobTestMethod" cron="*/10 * * * * ?" /> </task:scheduled-tasks> <bean id="quartzTaskBean" class="com.hs.service.QuartzTaskService"/>
然后在service这么写
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.hs.service; import org.joda.time.DateTime; import org.springframework.stereotype.Service; /** * * @author wishr */ @Service public class QuartzTaskService { public void quartzTest() { DateTime dt = new DateTime(); System.out.println(dt.toString()); } }