Cron trigger not firing for the specified timezone - java

I have list of timezones; and for each timezone, I have to start schedule job. Following is the code
cronexpr = 0 30 8,12,15,17 * * ?
if(cronexpr != null){
for(int i=0;i<tList.size();i++) {
job = new JobDetailImpl("runSMSJob"+i,"SMSJobgrp"+i,SMSJob.class);
trigger = new CronTriggerImpl("runMeJobTesting"+i, "group", "runSMSJob"+i, "SMSJobgrp"+i, cronexpr, tList.get(i));
logger.info("TIMEZONE is "+trigger.getTimeZone());
schd.start();
schd.scheduleJob(job, trigger);
}
Here tList is a list containing several timezones. On my local system its running properly but on server where the timezone is BST, even though the locale is India timezone, it's firing at the BST time.
Do any one have any idea on why its failing to take the specified timezone properly?

Related

Updating CroneSchedule & Job Dynamically without stopping server

I need help in externalizing the below cron schedule or executing it dynamically. For example, in the below code it is hardcoded to perform every Saturday: cronSchedule("0 0 12 ? * SAT"). I want the value inside the cronSchedule() to externalize so that even after the server is started, I can still change the cron schedule to Monday or every day based on my choice and it can be run. I am looking for suggestion in java and not in spring.
public void run() throws Exception {
// Getting a reference to a scheduler
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sched = sf.getScheduler();
// job will run every week at Saturday 12 Noon Server Time
JobDetail job = newJob(CachingJob.class).withIdentity("job1", "group1").build();
CronTrigger trigger = newTrigger().withIdentity("trigger1", "group1").withSchedule(cronSchedule("0 0 12 ? * SAT"))
.build();
Date ft = sched.scheduleJob(job, trigger);
sched.start();
SchedulerMetaData metaData = sched.getMetaData();
}
Any input or suggestion is appreciated.
We can perform below method to reschedule the job :
cronScheduler.rescheduleJob(cronTrigger.getKey(), newTrigger().withIdentity("customTrigger", "defaultGroup")
.withSchedule(cronSchedule(cronExpression)).build());

Java Quartz scheduler trigger nextFireTime is null

I am creating a Quartz trigger for various schedule frequencies.
At the end of the function I return the trigger, but debug output it before the return statement.
The debug output is this Trigger 'DEFAULT.6da64b5bd2ee-91b0fa99-6e11-4356-a55f-e80353b61fc4': triggerClass: 'org.quartz.impl.triggers.DailyTimeIntervalTriggerImpl calendar: 'null' misfireInstruction: -1 nextFireTime: null.
I am worried about nextFireTime being null, will the trigger still fire?
Part of the code looks like this:
if (freqType.equalsIgnoreCase(KpiDefinition.KPI_FREQ_TYPE_DAILY)
|| freqType
.equalsIgnoreCase(KpiDefinition.KPI_FREQ_TYPE_SCHEDULED))
{
DailyTimeIntervalScheduleBuilder schedule = DailyTimeIntervalScheduleBuilder
.dailyTimeIntervalSchedule()
.startingDailyAt(startTime)
.endingDailyAt(endTime)
.onEveryDay()
.withInterval(kpiDef.getKpiFrequency().intValue(),
IntervalUnit.valueOf(kpiDef.getKpiFreqTimeUnit()))
.withMisfireHandlingInstructionIgnoreMisfires();
Date startDate = kpiDef.getKpiStartDate();
if (startDate.before(new Date()))
{
startDate = new Date();
}
if (freqType.equalsIgnoreCase(KpiDefinition.KPI_FREQ_TYPE_DAILY))
{
trigger = newTrigger().withSchedule(schedule)
.startAt(startDate).build();
} else if (freqType
.equalsIgnoreCase(KpiDefinition.KPI_FREQ_TYPE_SCHEDULED))
{
Date endDate = kpiDef.getKpiEndDate();
// This means that schedule has already passed and so KPI should
// not be scheduled.
if (endDate.before(new Date()))
{
logger.debug("getTriggerWithSchedule for KPI " + kpiDef.getKpiDefId() + " null Schedule returned for end date " +endDate.toString());
return null;
}
trigger = newTrigger().withSchedule(schedule)
.startAt(startDate).endAt(endDate).build();
}
}
nextFireTime is only resolved for CronTriggers in my experience. SimpleTrigger for example also has nextFireTime=null. So I wouldn't worry.
Bear in mind also this:
The value returned is not guaranteed to be valid until after the Trigger has been added to the scheduler.
http://www.quartz-scheduler.org/api/2.1.7/org/quartz/Trigger.html#getNextFireTime()

Google Cal - How to get completed/past events

I use the code below to fetch the user's calendar events for the current day.
TODAY_MS is a timestamp of the start of the day and ONE_DAY_MS is a day in milliseconds (1000 * 60 * 60 * 24).
However, this code only gets upcoming events. It doesn't return earlier events in the day.
(i.e.: If I run this at 3PM, it won't return an event that happened from 1 to 2 PM because the event is completed.)
How would I go about getting all of the events in a time period, including those who are completed?
Uri.Builder builder = WearableCalendarContract.Instances.CONTENT_URI.buildUpon();
ContentUris.appendId(builder, TODAY_MS);
ContentUris.appendId(builder, TODAY_MS + ONE_DAY_MS - 1);
final Cursor cursor = mContext.getContentResolver().query(builder.build(), null, null, null, null); // Could optimize this line for speed.
Thank you!
In Google Calendar API v3, under Events:list, you can use the parameter timeMin and timeMax for an event's time to filter.
Here's an sample of minimum and maximum time:
timeMin='2012-10-25T00:00:00Z'
timeMax='2012-10-26T00:00:00Z'
You may also get 2 different date like this:
// Start date from where to get the events
$query->setStartMin('2013-01-01');
// End date
$query->setStartMax('2013-03-20');

Returning time of last modification of file to Stata

I'm a Stata user trying to make use of Stata's Java API. I want to use Java to return the time of last modification of a file to Stata. However, I think I'm running into issues with time zones.
Quick background on times in Stata for non-Stata users: Times are represented by the number of milliseconds since January 1, 1960 00:00:00.000. Stata does not have time zones, so I want the return value from the Java function to be the number of milliseconds since midnight on January 1, 1960 in my time zone (America/New York).
Here is my attempt at the Java function (I can post it in its entirety if that would be helpful):
import com.stata.sfi.*;
// Other imports
public class SFileAttribs
{
// Syntax: lastModified(String filename, String scalar_name)
// Stores in the Stata scalar scalar_name the time of last
// modification of filename.
public static int lastModified(String[] args)
{
// Code here...
// Get the time.
FileTime time;
try {
time = (FileTime) Files.getAttribute(path, "lastModifiedTime");
}
catch (IOException e) {
SFIToolkit.errorln("file I/O error on read");
return(692);
/*NOTREACHED*/
}
// Store the time in the scalar.
Calendar cal1960 = Calendar.getInstance();
cal1960.set(1960, 0, 1, 0, 0, 0);
cal1960.set(Calendar.MILLISECOND, 0);
Scalar.setValue(args[1], time.toMillis() - cal1960.getTimeInMillis());
return(0);
}
}
Back in Stata, I run this command:
// Calls SFileAttribs.lastModified("Test.txt", "filetime").
javacall SFileAttribs lastModified, args("Test.txt" "filetime")
However, the result is an hour earlier than it should be:
. display %tc filetime
24oct2013 12:54:36
The time of last modification in my time zone is 13:54, not 12:54.
I am really struggling on this one and would appreciate any suggestions.
EDIT:
Perhaps predictably given that I'm coming from a language with no time zones, I think I messed up daylight savings. In my time zone, it is now DST, but in the same time zone in January 1, 1960, it was not DST. I need to account for that:
// Store the time in the scalar.
Calendar now = Calendar.getInstance();
Calendar cal1960 = Calendar.getInstance();
cal1960.set(1960, 0, 1, 0, 0, 0);
cal1960.set(Calendar.MILLISECOND, 0);
int dstHour = (cal1960.getTimeZone().inDaylightTime(cal1960.getTime()) ? 1 : 0) -
(now.getTimeZone().inDaylightTime(now.getTime()) ? 1 : 0);
cal1960.set(Calendar.HOUR, dstHour);
Scalar.setValue(args[1], time.toMillis() - cal1960.getTimeInMillis());
Is there an easier way to do this?
The community-contributed command filesys is the easiest way to do exactly what you want:
. findfile auto.dta
. filesys `r(fn)', attributes
. return list
macros:
(some output omitted)
r(accessednum) : "1871843910000"
r(modifiednum) : "1745362526000"
r(creatednum) : "1745362526000"
r(accessed) : "25apr2019 20:38:30"
r(modified) : "22apr2015 22:55:26"
r(created) : "22apr2015 22:55:26"
. display %tcHH:MM `r(modifiednum)'
22:55
You can install the filesys command by using the
community-contributed command github:
. net install github, from("https://haghish.github.io/github/")
. github install wbuchanan/StataFileSystem

Calculate client-server time difference in Borland Starteam server 8

Problem. I need a way to find Starteam server time through Starteam Java SDK 8.0. Version of server is 8.0.172 so method Server.getCurrentTime() is not available since it was added only in server version 9.0.
Motivation. My application needs to use views at specific dates. So if there's some difference in system time between client (where the app is running) and server then obtained views are not accurate. In the worst case the client's requested date is in the future for server so the operation results in exception.
After some investigation I haven't found any cleaner solution than using a temporary item. My app requests the item's time of creation and compares it with local time. Here's the method I use to get server time:
public Date getCurrentServerTime() {
Folder rootFolder = project.getDefaultView().getRootFolder();
Topic newItem = (Topic) Item.createItem(project.getTypeNames().TOPIC, rootFolder);
newItem.update();
newItem.remove();
newItem.update();
return newItem.getCreatedTime().createDate();
}
If your StarTeam server is on a Windows box and your code will be executing on a Windows box, you could shell out and execute the NET time command to fetch the time on that machine and then compare it to the local time.
net time \\my_starteam_server_machine_name
which should return:
"Current time at \\my_starteam_server_machine_name is 10/28/2008 2:19 PM"
"The command completed successfully."
We needed to come up with a way of finding the server time for use with CodeCollab. Here is a (longish) C# code sample of how to do it without creating a temporary file. Resolution is 1 second.
static void Main(string[] args)
{
// ServerTime replacement for pre-2006 StarTeam servers.
// Picks a date in the future.
// Gets a view, sets the configuration to the date, and tries to get a property from the root folder.
// If it cannot retrieve the property, the date is too far in the future. Roll back the date to an earlier time.
DateTime StartTime = DateTime.Now;
Server s = new Server("serverAddress", 49201);
s.LogOn("User", "Password");
// Getting a view - doesn't matter which, as long as it is not deleted.
Project p = s.Projects[0];
View v = p.AccessibleViews[0]; // AccessibleViews saves checking permissions.
// Timestep to use when searching. One hour is fairly quick for resolution.
TimeSpan deltaTime = new TimeSpan(1, 0, 0);
deltaTime = new TimeSpan(24 * 365, 0, 0);
// Invalid calls return faster - start a ways in the future.
TimeSpan offset = new TimeSpan(24, 0, 0);
// Times before the view was created are invalid.
DateTime minTime = v.CreatedTime;
DateTime localTime = DateTime.Now;
if (localTime < minTime)
{
System.Console.WriteLine("Current time is older than view creation time: " + minTime);
// If the dates are so dissimilar that the current date is before the creation date,
// it is probably a good idea to use a bigger delta.
deltaTime = new TimeSpan(24 * 365, 0, 0);
// Set the offset to the minimum time and work up from there.
offset = minTime - localTime;
}
// Storage for calculated date.
DateTime testTime;
// Larger divisors converge quicker, but might take longer depending on offset.
const float stepDivisor = 10.0f;
bool foundValid = false;
while (true)
{
localTime = DateTime.Now;
testTime = localTime.Add(offset);
ViewConfiguration vc = ViewConfiguration.CreateFromTime(testTime);
View tempView = new View(v, vc);
System.Console.Write("Testing " + testTime + " (Offset " + (int)offset.TotalSeconds + ") (Delta " + deltaTime.TotalSeconds + "): ");
// Unfortunately, there is no isValid operation. Attempting to
// read a property from an invalid date configuration will
// throw an exception.
// An alternate to this would be proferred.
bool valid = true;
try
{
string testname = tempView.RootFolder.Name;
}
catch (ServerException)
{
System.Console.WriteLine(" InValid");
valid = false;
}
if (valid)
{
System.Console.WriteLine(" Valid");
// If the last check was invalid, the current check is valid, and
// If the change is this small, the time is very close to the server time.
if (foundValid == false && deltaTime.TotalSeconds <= 1)
{
break;
}
foundValid = true;
offset = offset.Add(deltaTime);
}
else
{
offset = offset.Subtract(deltaTime);
// Once a valid time is found, start reducing the timestep.
if (foundValid)
{
foundValid = false;
deltaTime = new TimeSpan(0,0,Math.Max((int)(deltaTime.TotalSeconds / stepDivisor), 1));
}
}
}
System.Console.WriteLine("Run time: " + (DateTime.Now - StartTime).TotalSeconds + " seconds.");
System.Console.WriteLine("The local time is " + localTime);
System.Console.WriteLine("The server time is " + testTime);
System.Console.WriteLine("The server time is offset from the local time by " + offset.TotalSeconds + " seconds.");
}
Output:
Testing 4/9/2009 3:05:40 PM (Offset 86400) (Delta 31536000): InValid
Testing 4/9/2008 3:05:40 PM (Offset -31449600) (Delta 31536000): Valid
...
Testing 4/8/2009 10:05:41 PM (Offset 25200) (Delta 3): InValid
Testing 4/8/2009 10:05:38 PM (Offset 25197) (Delta 1): Valid
Run time: 9.0933426 seconds.
The local time is 4/8/2009 3:05:41 PM
The server time is 4/8/2009 10:05:38 PM
The server time is offset from the local time by 25197 seconds.
<stab_in_the_dark>
I'm not familiar with that SDK but from looking at the API if the server is in a known timezone why not create and an OLEDate object whose date is going to be the client's time rolled appropriately according to the server's timezone?
</stab_in_the_dark>

Categories

Resources