Spring+Schedule(定时任务)小示例

本篇文章简单介绍一个Spring的schedule小例子。此定时任务放在一个mvc工程里面,配置以及代码都可以参考[url]http://fengyilin.iteye.com/admin/blogs/2338830[/url]这篇文章,下面主要把关于schedule的内容记录下来。

变更点:
1.在servlet-context.xml文件中引入schedule的配置文件


<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->

<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven>

</annotation-driven>

<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources/ directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources
in the /WEB-INF/views directory -->
<!-- <beans:bean -->
<!-- class="org.springframework.web.servlet.view.InternalResourceViewResolver"> -->
<!-- <beans:property name="prefix" value="/WEB-INF/views/" /> -->
<!-- <beans:property name="suffix" value=".jsp" /> -->
<!-- </beans:bean> -->
<beans:bean id="templateResolver"
class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".html" />
<!-- Template cache is true by default. Set to false if you want -->
<!-- templates to be automatically updated when modified. -->
<beans:property name="cacheable" value="false" />
</beans:bean>
<!-- SpringTemplateEngine automatically applies SpringStandardDialect and -->
<!-- enables Spring's own MessageSource message resolution mechanisms. -->
<beans:bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
<beans:property name="templateResolver" ref="templateResolver" />
</beans:bean>

<beans:bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<beans:property name="templateEngine" ref="templateEngine" />
</beans:bean>

<!-- Imports user-defined @Controller beans that process client requests -->
<beans:import resource="controllers.xml" />

<!-- Imports user-defined @Scheduled beans that process schedule tasks -->
<beans:import resource="schedules.xml" />

</beans:beans>



在此文件的最后一行引入了schedules.xml
2.追加schedules.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:task="http://www.springframework.org/schema/task"
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.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!--扫描schedule类package-->
<context:component-scan base-package="test.spring.schedule"/>
<!--使用spring scheduled的核心配置,启动scheduled注解功能-->
<task:annotation-driven />
</beans>


3.追加具体执行任务的类

/**
*
*/
package test.spring.schedule;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
* @author dwxx-116
*
*/
@Component
public class MySchedule {
private static final Log logger = LogFactory.getLog(MySchedule.class);
@Scheduled(fixedRate=2000)
public void processQueues() {
logger.info("start to processQueues,time:" + System.currentTimeMillis());
}
}



本示例只是简单的做了测试,定时任务每2秒钟重复执行一次,当然spring Scheduled通过cron表达式支持更加灵活的调度配置。

4.追加依赖jar包aopalliance-1.0.jar

最终的工程目录
[img]http://dl2.iteye.com/upload/attachment/0121/3646/0e4e19e7-64a7-3227-bdf1-25131a4514fa.jpg[/img]


完整的工程代码请参考附件
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Spring Boot和Quartz实现定时任务管理,可以让你更方便地管理和监控你的定时任务。下面是一个使用Spring Boot、Quartz和Spring MVC实现定时任务管理的示例: 首先,在你的Spring Boot应用程序中添加Quartz和Spring MVC的依赖项: ```xml <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 然后,在你的Spring Boot应用程序中创建一个Quartz的调度器,并添加一个Spring MVC的Controller来管理定时任务: ```java @Configuration public class QuartzConfig { @Bean public SchedulerFactoryBean schedulerFactoryBean() { SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean(); schedulerFactoryBean.setTriggers(myTaskTrigger().getObject()); return schedulerFactoryBean; } @Bean public JobDetailFactoryBean myTaskJob() { JobDetailFactoryBean jobDetailFactoryBean = new JobDetailFactoryBean(); jobDetailFactoryBean.setJobClass(MyTask.class); return jobDetailFactoryBean; } @Bean public CronTriggerFactoryBean myTaskTrigger() { CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean(); cronTriggerFactoryBean.setJobDetail(myTaskJob().getObject()); cronTriggerFactoryBean.setCronExpression("0/5 * * * * ?"); // 每5秒执行一次 return cronTriggerFactoryBean; } } @RestController public class TaskController { @Autowired private Scheduler scheduler; @PostMapping("/tasks") public void addTask(@RequestBody TaskInfo taskInfo) throws SchedulerException { JobDetail jobDetail = JobBuilder.newJob(taskInfo.getJobClass()) .withIdentity(taskInfo.getJobName(), taskInfo.getJobGroup()) .build(); CronTrigger trigger = TriggerBuilder.newTrigger() .withIdentity(taskInfo.getTriggerName(), taskInfo.getTriggerGroup()) .withSchedule(CronScheduleBuilder.cronSchedule(taskInfo.getCronExpression())) .build(); scheduler.scheduleJob(jobDetail, trigger); } @DeleteMapping("/tasks/{jobName}/{jobGroup}") public void deleteTask(@PathVariable String jobName, @PathVariable String jobGroup) throws SchedulerException { JobKey jobKey = new JobKey(jobName, jobGroup); scheduler.deleteJob(jobKey); } } ``` 在上面的代码中,我们创建了一个Spring MVC的Controller来管理定时任务。我们使用了Scheduler类来添加和删除定时任务。在添加定时任务时,我们使用了TaskInfo类来封装定时任务的信息。在删除定时任务时,我们使用了jobName和jobGroup来识别定时任务。 最后,在你的定时任务类中实现Job接口,并在类上添加@DisallowConcurrentExecution注解,以确保每个任务执行时只有一个实例: ```java @Component @DisallowConcurrentExecution public class MyTask implements Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { // 定时任务执行的代码 } } ``` 以上就是使用Spring Boot、Quartz和Spring MVC实现定时任务管理的示例

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值