使用spring scheduler完成定时调度

在applicationContext-task.xml中的配置:

<?xml version="1.0" encoding="UTF-8"?>
<!-- Spring的配置文件,需要引入schema: 让xml中的标签不能随便写 -->
<beans 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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/task
        http://www.springframework.org/schema/task/spring-task.xsd"
	default-autowire="byName">


	<!-- 指定任务 并行执行-->
	<task:scheduler id="scheduler" pool-size="10" />
	<task:scheduled-tasks scheduler="scheduler" >
		<!-- ref:spring容器中的bean method:定时执行method指定的方法 cron:表达式,和linux中crond的表达式一样;不过从秒开始的 
			*/5 * * * * ?:每隔5秒钟执行 秒 分 小时 天(月) 月(0-11) 天(星期) 2/5 * * * * ?:每隔5秒钟的第2秒运行(延迟2秒运行) 
			* */1 * * * ?:每隔1分钟执行一次 5,12,17 * * * * ?:5,12,17执行,其它的时间不执行 -->
		<!-- 定时统计 -->
		<task:scheduled ref="springTask" method="twoMin" cron="0 */2 * * * ?" />
	</task:scheduled-tasks>
</beans>

将applicationContext-task.xml中的配置引入到web.xml中

<!-- SpringMVC配置开始 -->
	<servlet>
		<servlet-name>DispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- tomcat一启动就初始化此Servlet -->
		<load-on-startup>1</load-on-startup>
		<!-- Spring的配置文件 -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<!-- classpath*:从所有的classpath中找配置文件,包含jar中的配置文件 -->
			<param-value>
				classpath*:META-INF/spring/applicationContext-*.xml,
				classpath*:META-INF/spring/*-applicationContext.xml
			</param-value>
		</init-param>
	</servlet>

测试看能不能执行:

@Component("springTask")
public class SpringTask extends BaseController{
	
	
	/**
	 * scheduler
	 * 每两分钟执行一次
	 */
	public void twoMin()
	{
		Date date = new Date();
		String dateToStr = this.dateUtil.dateToStr(date, "yyyy-MM-dd HH:mm:ss");
		System.out.println("两分钟执行一次定时任务  "+dateToStr);
	}

}

执行效果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

散装程序猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值