How to set an alarm to fire properly at fixed time?

后端 未结 3 1503
鱼传尺愫
鱼传尺愫 2020-12-14 05:16

I have this code

Calendar c = new GregorianCalendar();
        c.add(Calendar.DAY_OF_YEAR, 1);
        c.set(Calendar.HOUR_OF_DAY, 23);
        c.set(Calenda         


        
3条回答
  •  孤城傲影
    2020-12-14 06:22

    I had success with the following code, if you only want to set the alarm for the next occurance of hh:mm

    Calendar cal = new GregorianCalendar();
        cal.setTimeInMillis(System.currentTimeMillis());
        cal.set(Calendar.HOUR_OF_DAY, 22);
        cal.set(Calendar.MINUTE, 19);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        //check if we want to wake up tomorrow
        if (System.currentTimeMillis() > cal.getTimeInMillis()){
            cal.setTimeInMillis(cal.getTimeInMillis()+ 24*60*60*1000);// Okay, then tomorrow ...
        }
    

提交回复
热议问题