1.Timer 和TimerTask的使用
Timer t = new Timer();
TimerTaskE task = new TimerTaskE();
t.schedule(task,Date d);
TimerTaskE extends TimerTask{
public void run(){
Syso("sssss");
}
}
2.schedule()方法解释
在特定时间执行任务,只执行一次
public void schedule(TimerTask task,Date time)
在特定时间之后执行任务,只执行一次
public void schedule(TimerTask task, long delay)
指定第一次执行的时间,然后按照间隔时间,重复执行
public void schedule(TimerTask task, Date firstTime, long period)
在特定延迟之后第一次执行,然后按照间隔时间,重复执行
3.自定义定时器
4.spring定时器
(1)使用Timer处理
public class MainTask extends TimerTask{
@Override
public void run() {
System.out.println("检测用户是否掉线");
}
}
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="mainTask" class="org.time.MainTask"></bean>
<!-- 注册定时器信息 -->
<bean id="springTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
<!-- 延迟1秒执行首次任务 -->
<property name="delay" value="1000"></property>
<!-- 每隔2秒执行一次任务 -->
<property name="period" value="2000"></property>
<!-- 具体执行的任务 -->
<property name="timerTask" ref="mainTask"></property>
</bean>
<!-- 配置任务调度器工厂 -->
<bean id="timerFactory" class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list>
<ref bean="springTask"/>
</list>
</property>
</bean>
</beans>
(2)使用quartz
spring-context.jar和quartz.jar包
定时器类不需要继承自任何类,自己写个类,写个执行方法即可
<?xml version="1.0" encoding="GBK"?><beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
default-autowire="byName">
<bean id="helloWorker" class="com.jd.service.meeting.worker.MyWorker"></bean>
<bean id="startQuertz" lazy-init="false" autowire="no"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<bean class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail">
<bean
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="concurrent">
<value>false</value>
</property>
<property name="targetObject">
<ref bean="helloWorker" />
</property>
<property name="targetMethod">
<value>running</value>
</property>
</bean>
</property>
<property name="cronExpression">
<value>0/10 * * * * ?</value>
</property>
</bean>
</list>
</property>
</bean>
</beans>