欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java定时器

程序员文章站 2022-06-09 16:42:11
...

什么是定时器:

Java中定时器用于在特定时间运行指定的Java程序,其实现方式有两种:TimerTask和Quartz,其中Quartz最为常用,接下来演示如何在Spring框架中配置Quartz定时器:

Quartz下载地址:http://www.quartz-scheduler.org/downloads/

文件结构:

java定时器

切记,jar包别考错了,这里aop包不用拷贝。

test类:
 

package com.jd.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

	public static void main(String[] args) throws InterruptedException {
		ClassPathXmlApplicationContext applicationContext=  new ClassPathXmlApplicationContext("application.xml");
		Thread.sleep(5000);
		applicationContext.close();
	}
}

 

BackupJob类:

package com.jd.job;

import java.util.Date;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class BackupJob extends QuartzJobBean {

	private Date date;
	private String message;

	@Override
	protected void executeInternal(JobExecutionContext job) throws JobExecutionException {
		System.out.println("message = " + message);
		System.out.println(date + " 正在备份数据... ");
	}

	public Date getDate() {
		return date;
	}
	public void setDate(Date date) {
		this.date = date;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
}

配置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:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

<bean id="jobDetail" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
  <property name="jobClass" value="com.jd.job.BackupJob"></property>
  <!--  jobDataAsMap用于为任务成员变量赋值-->
  <property name="jobDataMap">
  <map>
    <entry key="url" value="jdbc:mysql:127.0.0.1:/3306/test"></entry>
  </map>
  </property>
</bean>

<!-- 指定Job什么时候触发 -->
<bean id="trigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
<property name="jobDetail" ref="jobDetail"></property>
<property name="startDelay" value="1000"></property>
<property name="repeatInterval" value="1000"></property>
</bean>


<!-- SchedulerFactoryBean配置调度器工厂	-->
	<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		<!-- 配置触发器 -->
		<property name="triggers">
			<array>
				<ref bean="trigger" />
			</array>
		</property>
	</bean>
</beans>

运行结果:

java定时器

xml可以改为:

<bean id="trigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="jobDetail"></property>
<property name="cronExpression" value="0 0 12 * * ?"></property>
</bean>

作用:指定某个时间可以进行任务。