A timer program in java

Source: Internet
Author: User

Encapsulate a class by yourself

The code is as follows: Copy code

Package com. anllin. utils;

Import java. text. DateFormat;
Import java. text. ParseException;
Import java. text. SimpleDateFormat;
Import java. util. Date;
Import java. util. concurrent. ScheduledThreadPoolExecutor;
Import java. util. concurrent. TimeUnit;

Public class ScheduleUtil
{
Private static DateFormat format ()
    {
Return new SimpleDateFormat ("HH: mm: ss: SSS ");
    }

Private static Date parseTime (String time) throws ParseException
    {
Return format (). parse (time );
    }

Private static long getOneDayMilliseconds ()
    {
Return 24*60*60 * 1000L;
    }

Private static long getMillisecondsInOneDayBetween (String now, String future) throws ParseException
    {
Date nowDate = parseTime (now );
Date futureDate = parseTime (future );
Long nowTime = nowDate. getTime ();
Long futureTime = futureDate. getTime ();
If (futureTime> nowTime)
        {
Return futureTime-nowTime;
        }
Else
        {
Return (futureTime + getOneDayMilliseconds ()-nowTime;
        }
    }

Public static void scheduleEveryday (ScheduledThreadPoolExecutor executor, Runnable command,
String executedEverydayAt) throws ParseException
    {
Long initialDelay = getMillisecondsInOneDayBetween (format (). format (new Date (), executedEverydayAt );
Long period = getOneDayMilliseconds ();
Executor. scheduleAtFixedRate (command, initialDelay, period, TimeUnit. MILLISECONDS );
    }
}

Call method

The code is as follows: Copy code

Public static void main (String [] args) throws Exception
    {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor (5 );
String executedEverydayAt = "12: 00: 00: 000 ";
ScheduleUtil. scheduleEveryday (executor, new Runnable (){
Public void run ()
            {
System. out. println ("executing business logic ");
            }
}, ExecutedEverydayAt );
    }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.