同时上3种手段,保障Quartz不重复执行任务

Quartz是Java比较流行的定时任务框架,使用定时任务最烦的是不受控制的多线程,定时任务被重复执行。如何控制Quartz让定时任务不被重复执行呢?总结了3中方法和大家分享。

1. ##修改Quartz的默认线程数,从默认10个线程改为1个线程。
配置如下:
schedulerFactoryBean添加属性:configLocation。quartz.properties在Quartz.jar包中拷贝。

	<bean id="schedulerFactoryBean"
		class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		<property name="triggers">
			<list>
				<ref bean="cronTrigger"></ref>
			</list>
		</property>
		<property name="configLocation" value="classpath:quartz.properties"></property>
	</bean>

quartz.properties配置

org.quartz.scheduler.instanceName: DefaultQuartzScheduler
org.quartz.scheduler.rmi.export: false
org.quartz.scheduler.rmi.proxy: false
org.quartz.scheduler.wrapJobExecutionInUserTransaction: false
org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount: 1
org.quartz.threadPool.threadPriority: 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true
org.quartz.jobStore.misfireThreshold: 60000
org.quartz.jobStore.class: org.quartz.simpl.RAMJobStore

2. MethodInvokingJobDetailFactoryBean的concurrent属性设值为false

	<bean id="myJob"
		class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
		<property name="targetObject" ref="mySchedule"></property>
		<!-- 任务类中需要执行的方法 -->
		<property name="targetMethod" value="jobHandler"></property>
		<!-- 上一次未执行完成的,要等待有再执行。 -->
		<property name="concurrent" value="false"></property>
	</bean>

3. 多个待执行任务分别封装初始化时入队,执行时出队。
例如这样:

	public AdapterJob() {
		super();
		System.out.println("AdapterJob 初始化");
		//初始化一个队列
		queue = new LinkedBlockingDeque<Integer>();
		for (int i = 0; i < 50; i++) {
			queue.offer(i);
		}
		startTime = System.currentTimeMillis();
	}

	public void jobHandler() {
		String name = Thread.currentThread().getName();
		System.out.println(name);
		int i = queue.poll();
		System.out.println(i);
	}

运行效果
在这里插入图片描述

总结
以上3种措施一般使用一种就可以保证任务只执行一次,在一些可靠性要求高的定制任务执行场景可以考虑3中措施同时上,数据库的操作加并发锁。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

软件工程师文艺

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值