温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java中怎样实现定时任务

发布时间:2021-08-07 11:31:40 来源:亿速云 阅读:136 作者:Leah 栏目:编程语言

今天就跟大家聊聊有关Java中怎样实现定时任务,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

  一、普通thread

  这是最常见的,创建一个thread,然后让它在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) {

  // ------- code for task to run

  System.out.println("Hello !!");

  // ------- ends here

  try {

  Thread.sleep(timeInterval);

  } catch (InterruptedException e) {

  e.printStackTrace();

  }

  }

  }

  };

  Thread thread = new Thread(runnable);

  thread.start();

  }

  }

  二、用Timer和TimerTask

  上面的实现是非常快速简便的,但它也缺少一些功能。

  用Timer和TimerTask的话与上述方法相比有如下好处:

  1.当启动和去取消任务时可以控制

  2.第一次执行任务时可以指定你想要的delay时间

  在实现时,Timer类可以调度任务,TimerTask则是通过在run()方法里实现具体任务。

  Timer实例可以调度多任务,它是线程安全的。

  当Timer的构造器被调用时,它创建了一个线程,这个线程可以用来调度任务。

  下面是代码:

  代码如下:

  import java.util.Timer;

  import java.util.TimerTask;

  public class Task2 {

  public static void main(String[] args) {

  TimerTask task = new TimerTask() {

  @Override

  public void run() {

  // task to run goes here

  System.out.println("Hello !!!");

  }

  };

  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);

  } // end of main

  }

  这些类从JDK 1.3开始存在。

  三、ScheduledExecutorService

  ScheduledExecutorService是从Java SE 5的java.util.concurrent里,做为并发工具类被引进的,这是最理想的定时任务实现方式。

  相比于上两个方法,它有以下好处:

  1.相比于Timer的单线程,它是通过线程池的方式来执行任务的

  2.可以很灵活的去设定第一次执行任务delay时间

  3.提供了良好的约定,以便设定执行的时间间隔

  下面是实现代码,我们通过ScheduledExecutorService#scheduleAtFixedRate展示这个例子,通过代码里参数的控制,首次执行加了delay时间。

  代码如下:

  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

  .newSingleThreadScheduledExecutor();

  service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);

  }

  }

看完上述内容,你们对Java中怎样实现定时任务有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI