当前位置: 移动技术网 > IT编程>开发语言>Java > Java Web项目中编写定时任务的实现

Java Web项目中编写定时任务的实现

2019年07月22日  | 移动技术网IT编程  | 我要评论

之前在的公司有专门的任务调度框架,需要使用的时候引个jar包加个配置和注解就可以使用了,还有专门的平台来维护运行的机器及监控执行状态等等。

现在突然没了这个工具,而又要写定时任务,该怎么办呢?

对于非web应用来说,我们可以使用quartz,使用简单,功能强大。

对于java web应用来说,当然也可以使用quartz(有一篇介绍了方法:),但是还有更方便的工具,那就是spring自带的支持定时任务功能。

spring的定时任务在spring-context中,简单配置的模板如下:

<?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" 
  xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
  http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd"> 
 
 <task:scheduler id="scheduler" pool-size="200"/> 
 <task:scheduled-tasks> 
  <!-- 你的task --> 
  <task:scheduled ref="xxxtask" method="execute" cron="0 0 * * * ?"/> 
 </task:scheduled-tasks> 
 <task:annotation-driven scheduler="scheduler"/> 
</beans> 

其中task:scheduler指定了执行定时任务使用的scheduler,默认使用的是

org.springframework.scheduling.concurrent.threadpooltaskscheduler;

task:annotation-driven允许使用@async和@scheduled注解;

task:scheduler-tasks中定义了一个个task,其中执行周期可以使用cron表达式,还可指定延时或频率等方式。

有一个转换cron的在线工具挺好用,推荐给大家(注意这里可能会显示7个字符,去掉最后一个*即可):

接下来还有一个问题,通常我们的线上环境是集群环境,有多台机器,而这些定时任务通常只需要在一台上执行,如何来进行控制呢?

目前想到两种办法,分享给大家:

1. 使用redis全局缓存


2. 通过判断文件的方式

通过判断某文件是否存在,来决定是否执行任务(是否加载任务对应的spring配置文件),参考代码:

@component 
public class xxxlistener implements applicationcontextaware { 
 
 // 防止加载多次 
 private static final atomicinteger init_lock = new atomicinteger(0); 
 
 @override 
 public void setapplicationcontext(applicationcontext applicationcontext) throws beansexception { 
 
  if (init_lock.incrementandget() > 1) { 
   // 类已加载过 
   return; 
  } 
 
  resource resource = applicationcontext.getresource("classpath:<标识文件>"); 
  if (!resource.exists()) { 
   // 文件不存在,不启动 
   return; 
  } 
   
  classpathxmlapplicationcontext context = new classpathxmlapplicationcontext(applicationcontext); 
  context.setconfiglocations("classpath:spring/job.xml"); 
  context.refresh(); 
 } 
} 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网