创建简单的定时器

制作一个在固定时间触发的定时器,代码如下:

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class Test3 {
    public static void main(String[] args) {
        timer4();
    }


    public static void timer4() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 12); // 控制时
        calendar.set(Calendar.MINUTE, 0);    // 控制分
        calendar.set(Calendar.SECOND, 0);    // 控制秒

        Date time = calendar.getTime();     // 得出执行任务的时间,此处为今天的12:00:00
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask(){
        public void run(){
        System.out.println("***************");
        }
        }, time, 1000 * 60 * 60 * 24);// 这里设定将延时每天固定执行
   
    }
}


制作一个固定循环时间触发的定时器,代码如下:



public class Test2 {
    public static void main(String[] args) {
        final long timeInterval=60000;
        Runnable runnable= new Runnable(){
            public void run() {
                while(true){
                    System.out.println("你好!");
                  
                        try {
Thread.sleep(timeInterval);
} catch (InterruptedException e) {
   e.printStackTrace();
}                 
                }
            }
        };


        Thread thread=new Thread(runnable);
        thread.start();        
    }
}


按照参数制作定时器:

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;




public class Test4 {
    public static void main(String[] args) {
        Runnable runnable=new Runnable(){


            public void run() {
                System.out.println("我很好!");
            }
        };
        ScheduledExecutorService service=Executors.newSingleThreadScheduledExecutor();
        //第二个参数为首次执行的延时时间,第三个参数为定时执行的间隔时间
        service.scheduleAtFixedRate(runnable,10,20, TimeUnit.SECONDS);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值