/**
* 继承TimerTask实现定时任务
*/
public class MyTask extends TimerTask {
@Override
public void run() {
String currentTime = new SimpleDateFormat("yyy-MM-dd hh:mm:ss").format(new Date());
System.out.println(currentTime + " 定时任务正在执行...");
}
public static void main(String[] args) {
Timer timer = new Timer();
// 1秒钟执行一次的任务, 参数为: task, delay, peroid
timer.schedule(new MyTask(), 2000, 1000);
}
}
/**
* 定时调度业务类
*/
public class TaskService extends TimerTask {
private int count = 1;
public void run() {
System.out.println("第" + count + "次执行定时任务");
count++;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<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-2.5.xsd">
<bean id="taskService" class="com.zdp.service.TaskService"></bean>
<bean id="scheduledTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
<property name="timerTask" ref="taskService" />
<!-- 每隔一天执行一次配置: 24*60*60*1000 -->
<!-- 每1秒钟程序执行一次 -->
<property name="period" value="1000" />
<!-- 程序启动4秒钟后开始执行 -->
<property name="delay" value="4000" />
</bean>
<bean id="timerFactoryBean" class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list>
<ref bean="scheduledTimerTask" />
</list>
</property>
</bean>
</beans>
public class Main {
public static void main(String[] args) {
// 加载spring配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
System.out.println("<<-------- 启动定时任务 -------- >>");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
try {
if (reader.readLine().equals("quit")) {
System.out.println("<<-------- 退出定时任务 -------- >>");
System.exit(0);
}
} catch (IOException e) {
throw new RuntimeException("error happens...", e);
}
}
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有