NextExecution time with quartz definition fails when date if the end of the month - scala

Currently, I have a cron job scheduling for every minute but once the date is the end of the month, the nextExecution method fails to provide the proper date.
test("check execution times") {
// make sure the execution times are correct
val expression = "0 * * ? * * *" // every minute (the top of the minute)
val currentTime = "2019-12-31T00:00:00.000Z" // get current time
val expectedNextExecution = "2019-12-31T00:01:00.000Z" // get current time
val cron = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ)).parse(expression)
val executor = ExecutionTime.forCron(cron)
val actualNextExecution = executor.nextExecution(DateTime.parse(currentTime)).toString // call nextExecution which should give us the next top of the minute
// check if nextExecution has correct next execution time
assert(actualNextExecution == expectedNextExecution, "Wrong execution time")
}
Results :
Expected :"20[19-12-31T00:01]:00.000Z"
Wrong execution time Actual :"20[20-01-01T00:00]:00.000Z"

The answer to this was updating my cron-utils version.
Previously on:
4.1.0
Issue was fixed on:
9.0.2
Thank you

Related

Scraping Calendar data problem with next day date

Good morning, I have a problem that I do not know how to solve, through web-scraping I take data from the website where I work and create a ics calendar file with my shifts, it works almost always well, only when I have a shift that ends at midnight or later I get an error, this is because in the page I find only the start date and not the end date, so if I finish at 00.00 the correct date should be the next day, but it is added the same as the beginning so I get an error, do you have any idea how to correct this error?
"python nameerror free variable referenced before assignment in enclosing scope"
# CLEANING DATETIME DATUM
datclnd = soup_datum.replace('.', ' ')
dated = tempo.datetime.strptime(datclnd, "%d %m %Y")
yearclnd = dated.year
monthclnd = dated.month
dayclnd = dated.day
# CLEANING DATETIME DATUM
# CLEANING DATETIME HOUR AND MINUTES
time_split = soup_dienstbegin.split(":")
dienstBH = int(time_split[0])
dienstBM = int(time_split[1])
#dienstende
time_split2 = soup_dienstende.split(":")
dienstEH = int(time_split2[0])
try:
dienstEM = int(time_split2[1])
except:
NOTHING
def ics_working():
event = Event()
event['uid'] = f'19970610T172345Z-AF23B2#{dayclnd}{monthclnd}{yearclnd}'
event.add('summary', f'{string1}{tagesinfo2} {soup_kommentar2} {kursinfo}')
event.add('description', f'{schiffinfo}Schichtdauer: {soup_schichtdauer}, Bezahlte Zeit: {soup_bezahltezeit}\n, Infos: {schiffinfo}')
event.add('dtstart', datetime(yearclnd,monthclnd,dayclnd,dienstBH,dienstBM,0))
event.add('dtend', datetime(yearclnd,monthclnd,dayclnd,dienstEH,dienstEM,0))
event.add('dtstamp', datetime(yearclnd,monthclnd,dayclnd,dienstBH,dienstBM,0))
organizer = vCalAddress(f'MAILTO:{receiver_email}')
organizer.params['cn'] = vText(f'{username} Monatsplan')
organizer.params['role'] = vText(f'{username} Monatsplan')
event['organizer'] = organizer
event['location'] = vText('Werftestrasse 5, 6002 Luzern')
# Adding events to calendar
cal.add_component(event)
# Printing working day info
print(f'Datum: {soup_datum} Dienst: {string1}{tagesinfo2} --> Mannschaft: {crew_list2} --> OK')
ics_working()

How to get the quartz getNextFiretime (Java)

I am working on my automation project where I need trigger some functionality for every 8 hours to see if the expected web element is displayed. I am using the quartz scheduler to trigger the functionality for every 8 hours.
When I run the code, the nextfireTime is displayed for the 1st iteration. once the first iteration is completed, the code is waiting for the next iteration. But the time is not printed in the log. How can do that?
StdSchedulerFactory factory = new StdSchedulerFactory();
Scheduler scheduler = factory.getScheduler();
JobDetail Job1 = JobBuilder.newJob(myJob.class).build();
Trigger t1 = TriggerBuilder.newTrigger().withIdentity("cronTrigger1","group1").withSchedule(CronSchedulerBuilder.cronSchedule ("0/3 0 0 ? * * *)).build();
while (!elementtext.contains("***************"))
{
Date Currenttime = new Date();
Date date = scheduler.schedulejob(job1,t1);
scheduler.start();
log.info(job1.key() + will run at : +t1.getNextFiretime());
}
if (elementtext.contains("**********")){
scheduler.shutdown();
}
I expect the time to be displayed after the 1st run. But it is not displayed.

Anylogic Variable Not Updating

I an using a discrete event simulator in AnyLogic. I am having an issue with some code which updates a variable in my simulation. I store both the datetime at which the agent leaves the source block and the datetime at which it enters the sink block. I am trying to record the number of "rule breaks" for all agents. The rule break is defined below (two ways to break):
1) If the agent is received before a certain time (called SDC) and the agent is not completed by 5pm the same day, then the agent has broken the rule
2) If the agent is not completed by the next day at a certain time (called NDC), then the agent has broken the rule
I record a zero or a one for each agent if they break either rule in the variable called RuleBreak. However, in my simulation runs, the variable does not update at all. I hope I am just missing something small. Would appreciate any help! (code below)
Calendar received = Calendar.getInstance();
received.setTime(ReceivedDate);
Calendar completion = Calendar.getInstance();
completion.setTime(Completion);
Calendar SD_at_5 = Calendar.getInstance();
SD_at_5.setTime(ReceivedDate);
SD_at_5.set(Calendar.HOUR_OF_DAY,17);
SD_at_5.set(Calendar.MINUTE, 0);
SD_at_5.set(Calendar.SECOND, 0);
Calendar Tomorrow_at_NDC = Calendar.getInstance();
Tomorrow_at_NDC.setTime(ReceivedDate);
if(Tomorrow_at_NDC.get(Calendar.DAY_OF_WEEK) == 6)
Tomorrow_at_NDC.add(Calendar.DATE, 3);
else
Tomorrow_at_NDC.add(Calendar.DATE, 1);
Tomorrow_at_NDC.add(Calendar.DATE, 1);
Tomorrow_at_NDC.set(Calendar.HOUR_OF_DAY,NDC);
Tomorrow_at_NDC.set(Calendar.MINUTE, 0);
Tomorrow_at_NDC.set(Calendar.SECOND, 0);
int Either_rule_break = 0;
double time_diff_SDC = differenceInCalendarUnits(TimeUnits.SECOND,completion.getTime(),SD_at_5.getTime());
double time_diff_NDC = differenceInCalendarUnits(TimeUnits.SECOND,completion.getTime(),Tomorrow_at_NDC.getTime());
if((received.get(Calendar.HOUR_OF_DAY) < SDC) && (time_diff_SDC <= 0))
Either_rule_break = Either_rule_break + 1;
else
Either_rule_break = Either_rule_break + 0;
if((received.get(Calendar.HOUR_OF_DAY) >= SDC) && (time_diff_NDC <= 0))
Either_rule_break = Either_rule_break + 1;
else
Either_rule_break = Either_rule_break + 0;
if((Either_rule_break >= 1))
RuleBreak = RuleBreak + 1;
else
RuleBreak = RuleBreak + 0;
You haven't really explained where this code is used and what it receives. I assume the code is in a function, called in the sink's on-enter action, where ReceivedDate and Completion are Date instances stored per agent (source exit time and sink entry time, as dates, captured via AnyLogic's date() function).
And looks like your SDC hour-of-day is stored in SDC and your NDC hour-of-day in NDC (with RuleBreak being a variable in Main or similar storing the total number of rule-breaks).
Your calculations look OK except that the Tomorrow_at_NDC Calendar calculation seems wrong: you add 1 day twice (if not Saturday) or 3 days plus 1 day (if Saturday; in a Java Calendar, day-of-week 1 is Monday).
(Your Java is also very 'inefficient' with unnecessary extra local variables and performing logic when you don't need to; e.g., no point doing all the calendar preparation and check for your type 1 rule-break if the receive time is after the SDC hour.)
But are you sure there are any rule-breaks; how have you set up your model to ensure that there are (to test it)? Plus is RuleBreak definitely a variable outside of the agents that flow through your DES (i.e., in Main or similar)? Plus are Completion and ReceivedDate definitely stored per agent so, for example, if your function was called checkForRuleBreaks you would be doing something like the below in your sink on-exit action:
agent.Completion = date(); // Agent received date set earlier in Source action
checkForRuleBreaks(agent.ReceivedDate, agent.Completion);
(In fact, you don't need to store the completion date in the agent at all since that will always be the current sim-date inside your function and so you can just calculate it there.)

Playback historical data Akka Stream

Is it possible to emit data according to a defined clock with Akka Streams? Or do they just emit (ignoring backpressure) as fast as their data arrive? I'm particularly wondering if it's possible to playback historical data with a "mocked" clock, somehow using Source.tick perhaps.
It depends on what you mean by "defined clock".
Actual Wall Time
As you mentioned Source.tick is one possibility to get a clock of actual times coming from the system clock. The problem is that the Sink may not signal demand at a rate that is greater than or equal to the interval that the Source generates ticks. For example, your Sink may only signal demand once every minute but your interval in Source.tick may be 10 seconds. In this case the 5 intermediate ticks will be dropped, from the documentation:
If a consumer has not requested any elements at the point in time when
the tick element is produced it will not receive that tick element
later.
Simulated Time
It is always possible to simulate time using a Source.
We can first create a function that will simulate a clock using a start time, end time, and interval:
type MillisFromEpoch = Long
type MillisInterval = Long
val clock : (MillisFromEpoch, MillisFromEpoch, MillisInterval) => () => Iterator[MillisFromEpoch] =
(startTime, stopTime, interval) => () => new Iterator[MillisFromEpoch] {
var currentTime = startTime
override def hasNext : Boolean = currentTime < stopTime
override def next() : MillisFromEpoch = {
val returnMilis = currentTime
currentTime += interval
return returnMillis
}
}
This clock can now feed a Source. As an example we can create a clock that start at unix epoch and increments 1 second until the end of time:
val epoch : MillisFromEpoch = 0L
val second : MillisInterval = 1000L
val simulatedClockFromEpochSource : Source[MillisFromEpoch,_] =
Source fromIterator clock(epoch, Long.MaxValue, 1*second)
Or we can create a clock that starts now, and ends in 60 seconds incrementing by 5 second intervals:
val now : MillisFromEpoch = System.currentTimeMillis()
val simulatedClockFromNowSource : Source[MillisFromEpoch,_] =
Source fromIterator clock(now, now + 60*second, 5*second)
Sampling Frequency
There is a way to use Source.tick even when the downstream consumer is slower than the tick interval specified at the Source. We can create a Flow.filter that is constantly signaling demand to the Source but will only pass through times that are a defined increment apart.
We can start with a function that does the tracking of the time interval with an internal variable:
val frequencySample : (MillisInterval) => (MillisFromEpoch) => Boolean =
(interval) => {
var lastValidTime : MillisFromEpoch = -1
(timeToCheck) => {
if(lastValidTime < 0 || timeToCheck >= lastValidTime + interval) {
lastValidTime = timeToCheck
true
}
else {
false
}
}
}
And now this function can be used to create the Flow:
val frequencySampleFlow : (MillisInterval) => Flow[MillisFromEpoch, MillisFromEpoch, _] =
(frequency) => Flow[MillisFromEpoch] filter frequencySample(frequency)
Now we can create a Flow that has a slow frequency (e.g. 10 seconds) that is attached to a Source with a higher frequency (e.g. 1 second):
val slowFrequency : MillisInterval = 10 * second
//simulatedClockFromEpoch ticks every 1 second
//frequnencySampleFlow only passes every 10 second tick through
val slowSource =
simulatedClockFromEpochSource via frequencySampleFlow(slowFrequency)

VBSCRIPT - Have Current Time and a Duration and want to calculate start time based on these values

Example:
Time = 09:41:46
Duration = 0:00:17 (IE 17 seconds)
Start Time = Time - Duration
Clearly I can't just break this up into hours minutes and seconds and do a basic minus operation given the 60 minute hour and 60 second minute etc.
Can't seem to get my head around how to calculate this and hoping someone has come across this before :).
You can use the DateAdd function.
For example, this will subtract 17 seconds from the specified date/time.
DateAdd("s", -17, "1/1/2013 09:41:46")
Try this
Time = 09:41:46
Duration = 0:00:17
Start_Time = FormatDateTime(Time - Duration, 3)
wscript.echo hour(Start_Time)
wscript.echo minute(Start_Time)
wscript.echo second(Start_Time)
References:
https://www.w3schools.com/asp/asp_ref_vbscript_functions.asp#date