My application executes the following code:
// Check intakes every 15 minutes
Intent i = new Intent(this, IntakeReceiver.class);
i.putExtra("TYPE", "TAKEIN_CHECK");
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), 0, i, 0);
AlarmManager am = (AlarmManager)(this.getSystemService(Context.ALARM_SERVICE));
Calendar cal = Calendar.getInstance();
int offset = 1000 * 60 * 15; // 1000 * 60 * 15 (15 minutes)
long nowLastRounded = cal.getTimeInMillis() - (cal.getTimeInMillis() % offset);
am.setRepeating(AlarmManager.RTC_WAKEUP, nowLastRounded + offset, offset, pi);
// Also set alarm for 11:50 every day to notify about low stock
Intent i2 = new Intent(this, LowStockReceiver.class);
i2.putExtra("TYPE", "STOCK_CHECK");
PendingIntent pi2 = PendingIntent.getBroadcast(getApplicationContext(), 1, i2, 0);
long interval_day = AlarmManager.INTERVAL_DAY;
long interval_hour = AlarmManager.INTERVAL_HOUR;
int offset2 = 1000 * 60 * 60 * 11 + 1000 * 60 * 50; // 11:50
final int tzOffset = TimeZone.getDefault().getOffset(System.currentTimeMillis());
offset2 -= tzOffset;
nowLastRounded = cal.getTimeInMillis() - (cal.getTimeInMillis() % interval_day);
am.setRepeating(AlarmManager.RTC_WAKEUP, nowLastRounded + offset2, interval_hour, pi2);
The problem is that the LowStockReceiver.onReceive() is called every 15 minutes (like the IntakeReceiver.onReceive()) but it should only be called every hour starting from 11:50.
I have checked the value of nowLastRounded + offset2 and it equals the local time today at 11:50 converted to GMT. So it should run at 11:50, 12:50, 13:50, etc. (just for testing purposes currently).
Anyone have any idea what I could be doing wrong?
Thank you!
Your using same id for pending intent for both the alarm.use different id.
Solved my own problem.
The problem was two-fold but the question didn't contain enough details for the question to be solvable:
Above code was called as a static function from the main Application class which could get instantiated by the first alarm.
This caused the second alarm to be rescheduled, and the time appeared to be in the past, causing it to be fired immediately and confusing me.
Related
I check ical4j library. At time I need calculate event occurrences. Useful example to calculate is here. I try to shift start date and end date. In original start date is 20101113 - 2010 November, Saturday (it maps on pattern see BYDAY=...SA). I want do not care if start match or not. So I used start date with value 20101112 - 2010 November, Friday (it doesn't map on any day in pattern see BYDAY=MO,TU,SA)
VEvent event = new ContentBuilder().vevent {
dtstart('20101112', parameters: parameters() {value('DATE')})
dtend('20101113', parameters: parameters() {value('DATE')})
rrule('FREQ=WEEKLY;WKST=MO;INTERVAL=3;BYDAY=MO,TU,SA')
}
def dates = event.calculateRecurrenceSet(new Period('20101101T000000/20110101T000000'))
println dates
result is
[20101112T000000Z/20101113T000000Z, 20101113T000000Z/P1D, 20101129T000000Z/P1D, 20101130T000000Z/P1D, 20101204T000000Z/P1D, 20101220T000000Z/P1D, 20101221T000000Z/P1D, 20101225T000000Z/P1D]
almost as expected (except first period in result 20101112T000000Z/20101113T000000Z is redundant). So I continue investigate how to exclude one. In debug mode I see
result = {PeriodList#1497} size = 8
0 = {Period#2240} "20101112T000000Z/20101113T000000Z"
duration = null
rangeStart = {DateTime#2243} "20101112T000000Z"
rangeEnd = {DateTime#2244} "20101113T000000Z"
1 = {Period#2264} "20101113T000000Z/P1D"
duration = {Dur#2284} "P1D"
rangeStart = {DateTime#2285} "20101113T000000Z"
rangeEnd = {DateTime#2286} "20101114T000000Z"
2 = {Period#2265} "20101129T000000Z/P1D"
duration = {Dur#2284} "P1D"
rangeStart = {DateTime#2290} "20101129T000000Z"
rangeEnd = {DateTime#2291} "20101130T000000Z"
3 = {Period#2266} "20101130T000000Z/P1D"
duration = {Dur#2284} "P1D"
rangeStart = {DateTime#2295} "20101130T000000Z"
rangeEnd = {DateTime#2296} "20101201T000000Z"
4 = {Period#2267} "20101204T000000Z/P1D"
duration = {Dur#2284} "P1D"
rangeStart = {DateTime#2300} "20101204T000000Z"
rangeEnd = {DateTime#2301} "20101205T000000Z"
5 = {Period#2268} "20101220T000000Z/P1D"
duration = {Dur#2284} "P1D"
rangeStart = {DateTime#2315} "20101220T000000Z"
rangeEnd = {DateTime#2316} "20101221T000000Z"
6 = {Period#2269} "20101221T000000Z/P1D"
duration = {Dur#2284} "P1D"
rangeStart = {DateTime#2310} "20101221T000000Z"
rangeEnd = {DateTime#2311} "20101222T000000Z"
7 = {Period#2270} "20101225T000000Z/P1D"
duration = {Dur#2284} "P1D"
rangeStart = {DateTime#2305} "20101225T000000Z"
rangeEnd = {DateTime#2306} "20101226T000000Z"
Eureka! I've found marker to detect redundant dates in generated set (corrupted period has null duration). I continue handling it filtering periods with null value. But filter have filtered nothing. Continue checking...
package net.fortuna.ical4j.model;
...
public class Period extends DateRange implements Comparable<Period> {
private static final long serialVersionUID = 7321090422911676490L;
private Dur duration;
...
public final Dur getDuration() {
if (duration == null) {
return new Dur(getStart(), getEnd());
}
return duration;
}
...
as you can see, class Period has private Dur duration and public final Dur getDuration(). I can't access duration without workaround...
Question is
How should I do?
Use reflection hack to get duration - ugly solution.
Download library sources to change Period class and rebuild library - follows bad support new library versions.
Ask to ical4j developers to expand Period facade - it needs time to change and for release.
Use duration hack over toString (it's unreliable solution).
I've raised issue. I'will add details if they consider the issue.
I have block of code that allows me to retreive all the apps/services running on my android device including the app that I
am building. I am not entirely sure if I am on the right path butbecause I am debugging on android 4.3 I would like to use ActivityManager.RunningService.activeSince
(per service/app) and subtract it from SystemClock.elapsedRealtime(); which I understand is total milliseconds since reboot . So for example
if the device was rebboted at 10am and whatsapp was started at 10:15 and the current time is 1030 I want to be able to use these values
to get an a close estimate of the amount spent on whatsapp. I have a feeling that this is not the most elegant way to achieve this and I am therefore very open to
any advice. This my code below thus far . For now I am using android 4.3
ActivityManager am = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> services = am.getRunningServices(Integer.MAX_VALUE);
for (ActivityManager.RunningServiceInfo info : services) {
cal.setTimeInMillis(currentMillis-info.activeSince);
long millisSinceBoot = SystemClock.elapsedRealtime();
long appStartTime = info.activeSince;
long appDuration = appStartTime - millisSinceBoot ;
//long time = ((millisSinceBoot - values.get(position).activeSince)/1000);
//long time = ((millisSinceBoot - currentMillis-info.activeSince)/1000);
//Log.i("HRHHRHRHRHR", "%%%%%%%%%%%%%%%%"+time);
//String time1 = String.valueOf(time);
int seconds = (int) (appDuration / 1000) % 60 ;
int minutes = (int) ((appDuration / (1000*60)) % 60);
int hours = (int) ((appDuration / (1000*60*60)) % 24);
String time11 = hours+":"+minutes+":"+seconds;
Log.i("Time", "Secs:- " + seconds + " " + "Mins:- " + minutes + " " + "Hours:- " + hours);
Log.i(TAG, String.format("Process %s with component %s has been running since %s (%d milliseconds)",
info.process, info.service.getClassName(), cal.getTime().toString(), info.activeSince ));
}
I want to display the current cup usage and disk usage in two separate JProgressBars. And also it should update second by second. How to do it using java? I am quite new to java programming, so please give me some code example.
Thanks in advance.
You can use javasysmon-0.3.4.jar file to get the system related informations as CPU Usage,memory usage etc.
Some of the methods are listed below and if you want something else you can explore.
JavaSysMon monitor=new JavaSysMon();
//System.out.println("Operating System name is
"+monitor.osName());
long usersMillis = monitor.cpuTimes().getUserMillis();
/*System.out.println(String.format("User milli are %d days, %d
hr, %d min, %d sec",
TimeUnit.MILLISECONDS.toDays(usersMillis),
TimeUnit.MILLISECONDS.toHours(usersMillis),
TimeUnit.MILLISECONDS.toMinutes(usersMillis),
TimeUnit.MILLISECONDS.toSeconds(usersMillis)
));*/
long systemMillis = monitor.cpuTimes().getSystemMillis();
/*System.out.println(String.format("System milli are %d days, %d
hr, %d min, %d sec",
TimeUnit.MILLISECONDS.toDays(systemMillis),
TimeUnit.MILLISECONDS.toHours(systemMillis),
TimeUnit.MILLISECONDS.toMinutes(systemMillis),
TimeUnit.MILLISECONDS.toSeconds(systemMillis)
));*/
long idleMilli = monitor.cpuTimes().getIdleMillis();
/*System.out.println(String.format("Idle milli are %d days, %d
hr, %d min, %d sec",
TimeUnit.MILLISECONDS.toDays(idleMilli),
TimeUnit.MILLISECONDS.toHours(idleMilli),
TimeUnit.MILLISECONDS.toMinutes(idleMilli),
TimeUnit.MILLISECONDS.toSeconds(idleMilli)
));*/
/*CpuTimes time=new CpuTimes(usersMillis, systemMillis,
idleMilli);
cpuUsage=String.format("%.5f",
monitor.cpuTimes().getCpuUsage(time));*/
// System.out.println("CPU Usages "+String.format("%.5f",
monitor.cpuTimes().getCpuUsage(time)));
if(initialTime == null){
initialTime = monitor.cpuTimes();
}
cpuUsage = new
Float(monitor.cpuTimes().getCpuUsage(initialTime)).toString();
initialTime = monitor.cpuTimes();
long cpuUpTimeL = monitor.uptimeInSeconds()*1000;
float t = cpuUpTimeL/(float)(1000 * 60 * 60 * 24);
int days=(int) t;
t=t-days;
t= (t*24);
int hrs=(int) t;
t=t-hrs;
t=t*60;
int mins=(int) t;
t=t-mins;
t=t*60;
int secs=(int) t;
cpuUpTime=GetTotalTimeTakenInJourney.getTotalTimeTaken(days, hrs,
mins, secs);
// System.out.println("CPU Up time "+days+" days "+hrs+" hrs
"+mins+" mints "+secs+" seconds");
//System.out.println("CPU Numbers "+monitor.numCpus());
long totalBytes=monitor.physical().getTotalBytes();
totalRam=totalBytes/(float)(1024*1024*1024);
long freeBytes=monitor.physical().getFreeBytes();
freeRam=freeBytes/(float)(1024*1024*1024);
long ramUsages=totalBytes-freeBytes;
usedRam=ramUsages/(float)(1024*1024*1024);
You Could use tasklist command via this code
Runtime.getRuntime().exec(command)
I have a thread that runs every day at a given hour.
it gives me this error message :
2014-05-21 03:57:06 [CRITICAL][AlertMgr] : maintenance :
java.lang.IllegalArgumentException: timeout value is negative
at java.lang.Thread.sleep(Native Method)
at
com.orca.pf.tc50.managerutilities.maintenance.MaintenanceManager.backgroundProcess(Unknown
Source)
at
com.orca.pf.tc50.managerutilities.maintenance.MaintenanceManager.access$000(Unknown
Source)
at
com.orca.pf.tc50.managerutilities.maintenance.MaintenanceManager$1.run(Unknown
Source)
at java.lang.Thread.run(Thread.java:745).
do you know what could cause this.
Thanks
private void backgroundProcess()
{
Calendar cal;
cal = Calendar.getInstance();
log.addHelpField("AlertMgr");
/*
* Synchronise le calendrier a 3:00AM
*/
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
if (cal.get(Calendar.HOUR_OF_DAY) > HOUR_START)
{
/*
* wait till tomorrow
*/
cal.set(Calendar.HOUR_OF_DAY, HOUR_START);
cal.add(Calendar.DAY_OF_YEAR, 1);
}
else
{
cal.set(Calendar.HOUR_OF_DAY, HOUR_START);
}
do
{
try
{
/*
* Calculate the time to wait
*/
long timeToWait = cal.getTimeInMillis() - System.currentTimeMillis();
Thread.sleep(timeToWait);
processAllEntries();
/*
* wait for tomorrow
*/
cal.add(Calendar.DAY_OF_YEAR, 1);
/*
* Clear
*/
Thread.interrupted();
}
catch(InterruptedException i)
{
Thread.currentThread().interrupt();
}
catch(Exception ex)
{
log.addException(LogLevel.CRITICAL, "maintenance", ex);
}
}
while(!th.isInterrupted());
}
I have a recommendation for you , rather than using Thread.sleep() try looking into Java Timer class . It would simplify your task of scheduling job every x hours. It will save you the effort to compute the amount of time to sleep to schedule the next task. This class lets you focus on the Business logic and takes care of the job of scheduling your task.
I have time in seconds i want to convert it into a format like 6w 3d 9h 5m . Can someone please provide a method which can do this task. Thanks :)
w=weeks
d=days
h=hours
m=minutes
I have tried the below code but i dont get weeks using
int day = (int)TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) - TimeUnit.SECONDS.toHours(TimeUnit.SECONDS.toDays(seconds));
long minute = TimeUnit.SECONDS.toMinutes(seconds) - TimeUnit.SECONDS.toMinutes(TimeUnit.SECONDS.toHours(seconds));
System.out.println("Day :"+day+" Hours :"+hours+" Minutes :"+minute);
this will give you:
1w 4d 10h 20m
there should be more elegant way, but this works:
long s = 987654l;
final long M=60,H=60*M, D=24*H, W=7*D;
long w = s/W;
s%=W;
long d = s/D;
s%=D;
long h = s/H;
s%=H;
long m = s/M;
System.out.printf("%dw %dd %dh %dm",w,d,h,m);
int seconds=98765410;
int weeks = (int) (TimeUnit.SECONDS.toDays(seconds) / 7);
int days = (int) (TimeUnit.SECONDS.toDays(seconds) - 7 * weeks);
long hours = TimeUnit.SECONDS.toHours(seconds) - TimeUnit.DAYS.toHours(days) - TimeUnit.DAYS.toHours(7*weeks);
long minutes = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds) * 60);
System.out.println(weeks+"w "+days+"d "+hours+"h "+minutes+"m");
Will print out:
163w 2d 2h 50m