Spring注解@Scheduled定时任务
一、首先配置applicationContext-task.xml
(1)添加 xmlns:task="http://www.springframework.org/schema/task"
(2)添加 xsi:schemaLocation="http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"
------- applicationContext-task.xml文件 --------
<?xml version="1.0" encoding="UTF-8"?> <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-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-3.0.xsd"> <description>spring task定时任务</description> <!-- 定时任务配置 scheduler 方式 注解 --> <context:component-scan base-package="com.lwj.task" /> <task:executor id="executor" pool-size="5" /> <task:scheduler id="scheduler" pool-size="10" /> <task:annotation-driven executor="executor" scheduler="scheduler" /> </beans>
二、配置applicationContext.xml文件
------- applicationContext.xml文件 --------
<?xml version="1.0" encoding="UTF-8"?> <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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <!-- 开启注解扫描 --> <context:annotation-config /> <!--引入配置属性文件 --> <context:property-placeholder location="classpath:config.properties" /> <!--自动扫描含有@Service将其注入为bean 和@Repository注入 --> <context:component-scan base-package="com.lwj.service,com.lwj.dao" /> <!-- 定时任务 --> <import resource="applicationContext-task.xml" /> </beans>
三、编写TimeTask.java
------- TimeTask.java文件 --------
package com.lwj.task; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** * * @Description : 定时任务 * @author : lwj * @version : 1.0 * @Date : 2016年4月7日 上午8:56:00 */ @Component public class TimeTask { @Scheduled(cron="0/10 * * * * *") public void Test(){ System.out.println("每10秒执行一次任务!"); } }
效果图:
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
· 如何给本地部署的DeepSeek投喂数据,让他更懂你
· 超详细,DeepSeek 接入PyCharm实现AI编程!(支持本地部署DeepSeek及官方Dee
· 用 DeepSeek 给对象做个网站,她一定感动坏了
· .NET 8.0 + Linux 香橙派,实现高效的 IoT 数据采集与控制解决方案
· DeepSeek处理自有业务的案例:让AI给你写一份小众编辑器(EverEdit)的语法着色文件