Spring+Tomcat 定时任务
确定定时任务类所在的包被扫描到
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<!-- 可以扫描controller、service、...
这里让扫描controller,指定controller的包
-->
<context:component-scan base-package="com.**.controller"></context:component-scan>
<context:component-scan base-package="com.**.utils"/>
<!-- 使用注解 -->
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<mvc:resources mapping="/resource/**" location="/resource/"/>
<!--spring mvc的文件上传模块是可插拔的,默认没有启用,只要在 spring mvc 容器中实例化 MultipartResolver 接口的实现类即可,
spring mvc 为我们提供了整合了 commons-fileupload 的 CommonsMultipartResolver 解析器,只需实例化该类即可-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
<!-- 视图解析器
解析jsp解析,默认使用jstl标签,classpath下得有jstl的包
-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置jsp路径的前缀 -->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!-- 配置jsp路径的后缀 -->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
示例代码
package com.javapandeng.utils;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.javapandeng.mapper.MessageMapper;
import com.javapandeng.po.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* @Description:
* @Author be.insighted
* @Date 2022/12/17 20:34
*/
@Component
@EnableScheduling
public class ScheduleTask {
@Autowired
private MessageMapper messageMapper;
@Scheduled(cron = "0/30 * * * * ?")
public void saveMessage(){
Message message = new Message();
message.setName(RandomUtil.randomNumbers(6));
message.setContent(RandomUtil.randomString(6));
System.err.println("message内容:" + JSON.toJSONString(message));
messageMapper.insert(message);
}
}