java定时器学习
一、这个是利用jdk自带的Thread类的sleep方法实现定时执行任务。
package tasker;
import java.util.Date;
public class tasker01 extends Thread {
private static Date date;
public static void main(String[] args) {
while (true) {
try {
Thread.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("休眠一秒");
date = new Date();
System.out.println(date);
// 定时执行任务
}
}
}
二、利用 Java 自带的定时器任务执行类 java.util.Timer 和 java.util.TimerTask ,实现方式有两种,一种是用java匿名内部类实现,只需一个类即可,关于匿名内部类请参考http://www.cnblogs.com/nerxious/archive/2013/01/25/2876489.html,使用匿名内部类还有个前提条件:必须继承一个父类或实现一个接口。
package tasker; import java.util.Date;
import java.util.Timer; public class tasker02 {
public static void main(String[] args) { Timer timer = new Timer();
timer.schedule(task, 5000, 2000);
}
static java.util.TimerTask task = new java.util.TimerTask() { @Override
public void run() {
System.out.println("i am running");
Date date = new Date();
System.out.println(date);
}
}; }
第二种方式是新建一个类去继承TimerTask类,需要用两个类解决
Tasker类
package tasker; import java.util.Date;
import java.util.TimerTask; public class Tasker extends TimerTask{ @Override
public void run() {
System.out.println("i am running");
Date date=new Date();
System.out.println(date);
} }
main方法类
package tasker;
import java.util.Timer;
public class tasker02 {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new Tasker(), 5000, 2000);
}
}
再举个例子
package timer; import java.util.Timer;
import java.util.TimerTask; public class TestTimer {
public static void main(String[] args) {
System.out.println("About to schedule task.");
new Reminder(10);
System.out.println("Task scheduled...");
Timer timer=new Timer();
timer.schedule(new TaskTimer(), 3000);
}
public static class Reminder{
Timer timer;
public Reminder(int sec){
timer = new Timer();
timer.schedule(new TimerTask(){
public void run(){
System.out.println("Time's up...");
timer.cancel();
}
}, sec*1000);
}
} }
package timer;
import java.util.TimerTask;
public class TaskTimer extends TimerTask{
@Override
public void run() {
int m=4;
if(m==4){
System.out.println("====");
}else{
System.out.println("定时器运行.....");
}
}
}
三、使用ScheduledExecutorService类,此类改进了简陋的Timer类,Java提供的Time类可以周期性地或者延期执行任务,但是有时我们需要并行执行同样的任务,这个时候如果创建多个Time对象会给系统带来负担,解决办法是将定时任务放到线程池中执行。Java的ScheduledThreadPoolExecutor类实现了ScheduledExecutorService接口中定义的以不同方法执行任务的方法。
。
package tasker; import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; public class tasker03 { public static void main(String[] args) throws InterruptedException {
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5); System.out.println("Current Time = " + new Date());
for (int i = 0; i < 3; i++) {
Thread.sleep(1000);
scheduledThreadPool.scheduleWithFixedDelay(task, 10000,2000, TimeUnit.SECONDS);
} Thread.sleep(30000); scheduledThreadPool.shutdown();
while (!scheduledThreadPool.isTerminated()) {
}
System.out.println("Finished all threads");
}
static java.util.TimerTask task = new java.util.TimerTask() { @Override
public void run() {
System.out.println("i am running");
Date date = new Date();
System.out.println(date);
}
}; }
改进版的和多线程有关的定时器,有两个类
WorkerThread类
package tasker;
import java.util.Date;
public class WorkerThread implements Runnable {
private String command;
public WorkerThread(){};
public WorkerThread(String command){
this.command=command;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"start time:"+new Date());
processCommand();
System.out.println(Thread.currentThread().getName()+"end time:"+new Date());
}
private void processCommand(){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public String toString(){
return this.command;
}
}
main类
package tasker; import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; public class tasker03 { public static void main(String[] args) throws InterruptedException {
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
System.out.println("Current Time = " + new Date());
for (int i = 0; i < 3; i++) {
Thread.sleep(1000);
WorkerThread task=new WorkerThread("do something");
scheduledThreadPool.scheduleWithFixedDelay(task, 10000,2000, TimeUnit.SECONDS);
} Thread.sleep(30000); scheduledThreadPool.shutdown();
while (!scheduledThreadPool.isTerminated()) {
}
System.out.println("Finished all threads");
} }
四、使用任务调度框架Quartz,官网 http://www.quartz-scheduler.org
在Spring中的用法:
引入jar包
java代码
package com.coalmine.desktop;
import java.text.SimpleDateFormat;
import java.util.Date;
public class QuartzJob { public void work() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
System.out.println(sdf.format(date) + " 执行Quartz定时器"); }
}
applicationContext.xml配置如下:
<!-- 要调用的工作类 -->
<bean id="quartzJob" class="com.coalmine.desktop.QuartzJob"></bean> <!-- 定义调用对象和调用对象的方法 -->
<bean id="jobtask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<!-- 调用的类 -->
<property name="targetObject"> <ref bean="quartzJob" /> </property>
<!-- 调用类中的方法 -->
<property name="targetMethod">
<value>work</value>
</property>
</bean>
<!-- 定义触发时间 -->
<bean id="doTime" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail"> <ref bean="jobtask" /> </property>
<!-- cron表达式 -->
<property name="cronExpression">
<!-- 第 10秒 隔 5秒执行一次-->
<value>10/5 * * * * ?</value>
</property>
</bean>
<!-- 总管理类 如果将lazy-init='false'那么容器启动就会执行调度程序 -->
<bean id="startQuertz" lazy-init="false" autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list> <ref bean="doTime" /> </list>
</property>
</bean>
启动服务后从第10秒开始每隔5秒执行一次work方法
参考文档:http://www.quartz-scheduler.org/generated/2.2.2/pdf/Quartz_Scheduler_Developer_Guide.pdf
首先创建要执行的类。
然后初始化Scheduler,
SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory();
Scheduler sched = schedFact.getScheduler();
sched.start();
创建job
JobDetail job = newJob(HelloJob.class).withIdentity("myJob", "group1").build();
创建任务执行触发器
Trigger trigger = newTrigger().withIdentity("myTrigger", "group1").startNow()
.withSchedule(simpleSchedule()
.withIntervalInSeconds(40)
.repeatForever())
.build();
安排工作
// Tell quartz to schedule the job using our trigger
sched.scheduleJob(job, trigger);
关闭计划
sched.shutdown(true);
============================================================
The key interfaces of the Quar API are:
Scheduler - the main API for interacting with the Scheduler.
Job - an interface to be implemented by components that you want the Scheduler to execute.
JobDetail - used to define instances of Jobs.
Trigger - a component that defines the schedule upon which a given Job will be executed.
JobBuilder - used to define/build JobDetail instances, which define instances of Jobs.
TriggerBuilder - used to define/build Trigger instances.
java定时器学习的更多相关文章
- Java编程学习知识点分享 入门必看
Java编程学习知识点分享 入门必看 阿尔法颜色组成(alpha color component):颜色组成用来描述颜色的透明度或不透明度.阿尔法组成越高,颜色越不透明. API:应用编程接口.针对软 ...
- Java多线程学习(一)Java多线程入门
转载请备注地址:https://blog.csdn.net/qq_34337272/article/details/79640870 系列文章传送门: Java多线程学习(一)Java多线程入门 Ja ...
- Java的学习之路
记事本 EditPlus eclipse Java的学习软件,已经系统性学习Java有一段时间了,接下来我想讲一下我在Java学习用到的软件. 1.第一个软件:记事本 记事本是Java学习中最基础的编 ...
- Java多线程学习笔记
进程:正在执行中的程序,其实是应用程序在内存中运行的那片空间.(只负责空间分配) 线程:进程中的一个执行单元,负责进程汇总的程序的运行,一个进程当中至少要有一个线程. 多线程:一个进程中时可以有多个线 ...
- Java Web 学习路线
实际上,如果时间安排合理的话,大概需要六个月左右,有些基础好,自学能力强的朋友,甚至在四个月左右就开始找工作了.大三的时候,我萌生了放弃本专业的念头,断断续续学 Java Web 累计一年半左右,总算 ...
- Java基础学习-- 继承 的简单总结
代码参考:Java基础学习小记--多态 为什么要引入继承? 还是做一个媒体库,里面可以放CD,可以放DVD.如果把CD和DVD做成两个没有联系的类的话,那么在管理这个媒体库的时候,要单独做一个添加CD ...
- 20145213《Java程序设计学习笔记》第六周学习总结
20145213<Java程序设计学习笔记>第六周学习总结 说在前面的话 上篇博客中娄老师指出我因为数据结构基础薄弱,才导致对第九章内容浅尝遏止地认知.在这里我还要自我批评一下,其实我事后 ...
- [原创]java WEB学习笔记95:Hibernate 目录
本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...
- Java多线程学习(转载)
Java多线程学习(转载) 时间:2015-03-14 13:53:14 阅读:137413 评论:4 收藏:3 [点我收藏+] 转载 :http://blog ...
随机推荐
- HTTP API 设计指南(基础部分)
前言 这篇指南介绍描述了 HTTP+JSON API 的一种设计模式,最初摘录整理自 Heroku 平台的 API 设计指引 Heroku 平台 API 指引. 这篇指南除了详细介绍现有的 API 外 ...
- 在Linux环境下mysql的root密码忘记解决方法
MySQL密码的恢复方法之一 .首先确认服务器出于安全的状态,也就是没有人能够任意地连接MySQL数据库. 因为在重新设置MySQL的root密码的期间,MySQL数据库完全出于没有密码保护的 状态下 ...
- 【R】提升R代码运算效率的11个实用方法
低.有许多种方法可以提升你的代码运算效率,但或许你更想了解运算效率能得到多大的提升.本文将介绍几种适用于大数据领域的方法,包括简单的逻辑调整设计.并行处理和Rcpp的运用,利用这些方法你可以轻松地处理 ...
- SEO之基于thinkphp的URL伪静态
最近基于thinkphp开发了个导购网站,现在有时间,将遇到的伪静态问题整理下,与大家分享.1.设置URL伪静态在config.ini.php中设置,如果只想前台URL伪静态,那么只在前台的confi ...
- Python之批量改变图片大小
image_pylib模块:https://github.com/huangshiyu13/image_pylib data_engine模块:https://github.com/huangshiy ...
- Ubuntu系统启动报错:The system is running in low-graphics mode
最近,不小心将自己的Ubuntu-12.04桌面系统搞坏了,主要是由于改变了/var目录下文件的属主,结果桌面系统崩溃了,启动都成问题了.不过还算幸运,可以通过其他的机器登录到我的系统上.根据别人的系 ...
- 送给半路出家的Pythoner
伯乐在线Python专区: http://python.jobbole.com/category/python/ 我希望初学Python时就能知道的一些用法: http://python.jobbol ...
- 用 webpack 构建 node 后端代码,使其支持 js 新特性并实现热重载
https://zhuanlan.zhihu.com/p/20782320?utm_source=tuicool&utm_medium=referral
- [Scikit-learn] Dynamic Bayesian Network - Kalman Filter
看上去不错的网站:http://iacs-courses.seas.harvard.edu/courses/am207/blog/lecture-18.html SciPy Cookbook:http ...
- python处理文本文件
在测试任务过程中都或多或少遇到自己处理文本文件的情况. 举个栗子: 客户端测试从异常日志中收集有用信息. 后端测试需要创建各种规则的压力的词表. ... 这里给大家分享一个使用python脚本处理文本 ...