Spring Task 进行java定时任务
最近做了一个关于定时任务的程序,这里做个备份,以及我遇到的问题记录一下!
项目maven架构如下:

方式一:
1,配置文件application-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd">
<import resource="config/spring-config-*.xml" />
<bean id="ISystemLogReportEmailService" class="com.centaline.ibs.service.stats.report.impl.SystemLogReportEmailServiceImpl"></bean>
<task:scheduled-tasks >
<!-- 配置定时规则 配置定时任务 每天早上5:00 触发 -->
<task:scheduled ref="ISystemLogReportEmailService" method="TimeJob" cron="0 0 5 * * ?"/>
<task:scheduled ref="ISystemLogReportEmailService" method="TimeSendEmail" cron="0 30 9 * * ?"/>
</task:scheduled-tasks>
</beans>

注意:
一定要接口有这个定时任务方法,实现类中也要有,缺一不可,否则在项目启动时就会报错,说找不到task,,,,问题
2,新建一个符合你需求的定时任务
2.1接口中的定时方法:

2.2 实现类中的定时方法--具体逻辑按照你的需求

3,启动你的项目,在项目启动完成后
按照你上面的设置时间,就会调用你的定时任务 --亲测有效
在线 cron 表达式生成器:http://cron.qqe2.com/
例如:"0 15 10 * * ?" 每天上午10:15触发
方式二:
1,配置文件 spring-config-annotation.xml
<beans default-lazy-init="true"
xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd">
<mvc:annotation-driven conversion-service="conversionService" />
<!-- 扫描某某包下面使用@Component注解的类 将其实例化,放入spring容器中 -->
<context:component-scan base-package="com.centaline.*"/>
<!-- 启用定时任务的注解驱动 -->
<task:annotation-driven/>
<!-- 注:spring定时任务默认单线程,推荐配置线程池,若不配置多任务下会有问题。 -->
<task:scheduler id="poolTaskScheduler" pool-size="10"/>
</beans>
2,新建一个定时package com.centaline.spring_task; import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;/** * 使用 SpringTask 制作定时任务 */
@Component
public class SpringTask {
@Scheduled(cron = "0/1 * * * * ? ")
public void TimeJob(){
System.out.println("定时任务.....");
}
}
3,启动项目即可

备注点:不管是哪种方式,定时任务的方法都是不能带参数,否则会报错
如果有哪位大神,可以带参数,请告知,互相学习~~~

浙公网安备 33010602011771号