spring定时任务(@Scheduled注解)

本文介绍了如何在Spring MVC中利用@Scheduled注解创建定时任务,包括在XML中引入task命名空间、启用注解驱动、配置线程池以避免任务执行顺序问题,以及使用cron表达式设定执行时机。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 今天在实际工作中遇到了定时任务注解这个知识点,看了一下资料,整理一下,需要的同学可以大概参考,也为自己以后查阅记录这里。
  • 有可能有些地方有bug,大神路过请指点提出。

@1在springMVC里使用spring的定时任务非常简单,在xml里加入task的命名空间 

xmlns:task="http://www.springframework.org/schema/task"
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.0.xsd">

@2启用注解驱动的定时任务

<task:annotation-driven scheduler="myScheduler"/>

@3配置定时任务的线程池(推荐配置线程池,若不配置多任务下会有问题:(spring的定时任务默认是单线程多个任务执行起来时间会有问题(B任务会因为A任务执行起来需要10S而被延后10S执行);当我们配置了线程池后,(多线程下,B任务再也不会因为A任务执行起来要10S而被延后了))。

<task:scheduler id="myScheduler" pool-size="10"/>

@4写定时任务

   @Scheduled注解为定时任务,cron表达式里写执行的时机

package com.zyyc.job;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.zyyc.utils.JawaGlobals;
import com.zyyc.utils.JdbcUtils;

/**
 * Modified by zj on 2018/5/15.
 *
 * 创建设备心跳检测信息报警,每20分钟一次
 */
@Component
public class Heartbeat {
	protected static final transient Logger Log = Logger.getLogger(Heartbeat.class);	
	private static Map<String, Integer> hearttemp= new HashMap<String,Integer>(20);
	static{
		hearttemp.put("cook", 1);
		hearttemp.put("cook1", 0);
		hearttemp.put("PM25", 1);
		hearttemp.put("PM251", 0);
		hearttemp.put("PM10", 1);
		hearttemp.put("PM101", 0);
		
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值