Java Web项目中编写定时任务

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

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


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


对于Java Web应用来说,当然也可以使用Quartz(有一篇博客介绍了方法:http://blog.csdn.net/sadfishsc/article/details/50808027),但是还有更方便的工具,那就是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个字符,去掉最后一个*即可):

http://cron.qqe2.com/


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

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

1. 使用redis全局缓存

这个就不详细介绍了,可以参考下面两篇文章:

http://blog.csdn.net/lihao21/article/details/49104695

http://blog.csdn.net/liubenlong007/article/details/53782934

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();
    }
}


  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值