Spring定时器@Scheduled
以前用java自带的Timer做过定时器,但是在web项目中启动tomcat以后不能马上启动定时器,还需要手动触发,很不方便。于是就想到了在配置文件里直接写入。正好Spring有自带的定时器@Scheduled,所以做了个例子。
首先我是用的ssm框架,spring-mvc.xml文件整合了配置,当然别的框架也行,只要有Spring。
spring配置文件如下:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd "> <bean id="singer" class="com.timer.mytimer.MyTimer"/> <task:annotation-driven />
xmlns 多加下面的内容
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation多加下面的内容
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.1.xsd
ask任务扫描注解
<task:annotation-driven/>
最后是添加bean
<bean id="singer" class="com.timer.mytimer.MyTimer"/>
java代码
package com.timer.mytimer; import org.springframework.scheduling.annotation.Scheduled; public class MyTimer { public static void main(String[] args) { System.out.println("xxxx"); } //@Scheduled(cron="0/5 * * * * ? ") 每5秒执行一次 @Scheduled(fixedDelay=6000) // 每6秒执行一次 fixedDelay单位是毫秒 public void timeTigger(){ System.out.println("sssss"); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)