之前在的公司有专门的任务调度框架,需要使用的时候引个jar包加个配置和注解就可以使用了,还有专门的平台来维护运行的机器及监控执行状态等等。
现在突然没了这个工具,而又要写定时任务,该怎么办呢?
对于非Web应用来说,我们可以使用Quartz,使用简单,功能强大。
对于Java Web应用来说,当然也可以使用Quartz(有一篇介绍了方法:https://www.zzvips.com/article/90551.html),但是还有更方便的工具,那就是spring自带的支持定时任务功能。
Spring的定时任务在spring-context中,简单配置的模板如下:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<?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表达式,还可指定延时或频率等方式。
接下来还有一个问题,通常我们的线上环境是集群环境,有多台机器,而这些定时任务通常只需要在一台上执行,如何来进行控制呢?
目前想到两种办法,分享给大家:
1. 使用Redis全局缓存
https://www.zzvips.com/article/25666.html
2. 通过判断文件的方式
通过判断某文件是否存在,来决定是否执行任务(是否加载任务对应的spring配置文件),参考代码:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
@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();
}
}
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。
原文链接:http://blog.csdn.net/mj158518/article/details/54694589
相关文章
- 64M VPS建站:怎样优化以提高网站加载速度? 2025-06-10
- 64M VPS建站:是否适合初学者操作和管理? 2025-06-10
- ASP.NET自助建站系统中的用户注册和登录功能定制方法 2025-06-10
- ASP.NET自助建站系统的域名绑定与解析教程 2025-06-10
- 个人服务器网站搭建:如何选择合适的服务器提供商? 2025-06-10
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
-
2025-05-27 12
-
2025-05-25 75
-
2025-05-27 32
-
2025-06-05 88
-
2025-05-29 103

