码迷,mamicode.com
首页 > 编程语言 > 详细

java

时间:2017-12-26 21:07:22      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:system   rgs   period   方法   实例   code   span   lex   void   

1 java定时任务的实现方式

1.1 创建一个thread,run() while循环里sleep();

(简单粗暴)

public class Task1 {
    public static void main(String[] args) {
        // run in a second
        final long timeInterval = 1000;
        Runnable runnable = new Runnable() {
            public void run() {
                while (true) {
                    System.out.println("Hello !!");
                    // 试图使用线程休眠来实现周期执行,
                    try {
                        Thread.sleep(timeInterval);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
    }
}

1.2 使用Timer和Timer Task

  1. 当启动和去取消任务时可以控制
  2. 第一次执行任务时可以指定你想要的delay时间
import java.util.Timer;
import java.util.TimerTask;

public class HelperTest {
    public static void main(String[] args) {
        // TimerTask通过在run()方法里实现具体任务。
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                // task to run goes here
                System.out.println("Hello !!!");
            }
        };

        //Timer类可以调度任务。 Timer实例可以调度多任务,它是线程安全的。
        Timer timer = new Timer();
        long delay = 0;
        long intevalPeriod = 1 * 1000;
        // schedules the task to be run in an interval
        timer.scheduleAtFixedRate(task, delay, intevalPeriod);
    }
}

1.3 ScheduledExecutorService

比较理想的定时任务实现方式

  1. 相比于Timer的单线程,它是通过线程池的方式来执行任务的
  2. 可以很灵活的去设定第一次执行任务delay时间
  3. 提供了良好的约定,以便设定执行的时间间隔
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Task3 {
    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            public void run() {
                // task to run goes here
                System.out.println("Hello !!");
            }
        };
        ScheduledExecutorService service = Executors.ScheduledThreadPoolExecutor(1);
        // 第二个参数为首次执行的延时时间,第三个参数为定时执行的间隔时间
        service.scheduleAtFixedRate(runnable, 200L, 200L, TimeUnit.MILLISECONDS);
    }
}

java

标签:system   rgs   period   方法   实例   code   span   lex   void   

原文地址:https://www.cnblogs.com/eaglediao/p/7197907.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!