(转载)线程定时执行的两种实现方法

本文介绍了一种使用Java实现定时任务的方法,包括通过线程的sleep方法使线程休眠到指定时间点执行任务,以及使用Timer类的schedule方法来定时执行任务。文中还提供了将毫秒数转换为日期格式的实用函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package test;
 
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
 
public class TimerTest {
    public static void main(String[] args){    
        long now = System.currentTimeMillis();
         
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
        System.out.println("当前系统时间:" + df.format(new Date()));// new Date()为获取当前系统时间
        System.out.println("当前系统时间2: " + transferLongToDate("yyyy-MM-dd HH:mm:ss", now));
         
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 9);
        calendar.set(Calendar.MINUTE, 55);
        calendar.set(Calendar.SECOND, 0);
 
        long specTime = calendar.getTimeInMillis();
        <br>    //方法一: 使用线程的sleep方法,让线程休眠来达到按时执行的效果
        MyThread thread = new MyThread();
        try {
            Thread.sleep(specTime - now);
            thread.start();
        catch (InterruptedException e) {
            e.printStackTrace();
        }
    <br>    //方法二: 使用timer.schedule来实现定时执行线程,参数按如下方法执行即可
        /*Timer timer = new Timer();    
        timer.schedule(new MyTask(), specTime - now, 2000);//在1秒后执行此任务,每次间隔2秒执行一次,如果传递一个Data参数,就可以在某个固定的时间执行这个任务.    
         */
    }   
    // 使用内部类,来实现线程执行后,每隔两秒继续执行一次
    static class MyThread extends Thread{
        public void run(){
            System.out.println("________");
            MyThread thread = new MyThread();
            try {
                Thread.sleep(2000);
                thread.start();
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
     
      //使用内部类,利用TimerTask来实现线程的定时执行
    static class MyTimerTask extends java.util.TimerTask{     
        public void run(){    
            System.out.println("________");    
        }    
    }  
     
    /**
     * 把毫秒转化成日期
     * @param dateFormat(日期格式,例如:MM/ dd/yyyy HH:mm:ss)
     * @param millSec(毫秒数)
     * @return
     */
    public static String transferLongToDate ( String dateFormat, long millSec )
    {
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        Date date = new Date(millSec);
        return sdf.format(date);
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值