Demo entry 6660312

Test

   

Submitted by anonymous on Nov 15, 2017 at 04:00
Language: Java. Code size: 2.4 kB.

package timerStudy;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class HYTimer 
{
    private static Timer timer = new Timer();
    static public class MyTask1 extends TimerTask
    {
        @Override
        public void run()
        {
            System.out.println("MyTask1任务运行,运行时间为: " + new Date().toString());            
        }
    }
    static public class MyTask5 extends TimerTask
    {
        @Override
        public void run()
        {
            System.out.println("MyTask5任务运行,运行时间为: " + new Date().toString());

            try {
                Thread.sleep(0);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("MyTask5任务结束,运行时间为: " + new Date().toString());
            
        }
    }
    public static void main(String[] args)
    {
        HYTimer.test2();
    }
    
    /*开始时间在现在时间之后*/
    public static void test1()
    {
        MyTask1 task = new MyTask1();
        long nowTime = System.currentTimeMillis();
        /*任务在5秒之后运行*/
        Date taskTime = new Date(nowTime + 5000);
        System.out.println("预计将在: " + taskTime + "执行任务。"+ "\n当前时间为: " + new Date());
        timer.schedule(task, taskTime);  
    }
    
    /*固定循环值,按照现实时间算*/
    public static void test2()
    {
        MyTask5 task5 = new MyTask5();
        long nowTime = System.currentTimeMillis();
        Date newDate = new Date(nowTime - 36000);
        System.out.println("第一次预计将在: " + newDate + "执行任务。"+ "\n当前时间为: " + newDate);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        timer.schedule(task5, newDate, 6000);
    }
    /*固定循环值,按照执行时间算*/
    public static void test3()
    {
        MyTask5 task5 = new MyTask5();
        long nowTime = System.currentTimeMillis();
        Date newDate = new Date(nowTime-36000);
        System.out.println("第一次预计将在: " + newDate + "执行任务。"+ "\n当前时间为: " + newDate);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        timer.scheduleAtFixedRate(task5, newDate, 6000);
    }
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).