is it possible to use scheduleAtFixedRate to trigger a function every first of the month? - kotlin

I am new using kotlin and I am wondering if I can do the following...
I wanna call a method on the first of each month, I found this and saw a couple of examples like this:
timer.schedule(1000) {
println("hello world!")
}
I am wondering if is possible to use (instead of a fixed time) a calendar day? like first of the month?

There's no built-in way to do this.
If the exact time of day doesn't matter*, then one approach is to schedule a task to fire every 24 hours, and have it check whether the current time is the first day of the month, and if so, perform the task.
(* It will drift slightly when summer time starts or ends, or leap-seconds get added, but that may not be significant.)
A more powerful (but more complex approach) is to set the timer to go off once, at the appropriate time on the 1st of next month.  Then, after performing the task, it could re-schedule itself for the 1st of the following month.  (You'd need to take care that it always did so, even if the task threw an exception.)
You could put all this into a timer class of your own, to separate it from the business logic you want to run.
For examples in Java (which will translate directly to Kotlin/JVM), see the answers to these questions.

Related

Pyhon APScheduler stop jobs before starting a new one

I need to start a job every 30 minutes, but before a new job is being started I want the old but same job being terminated. This is to make sure the job always fetches the newest data file which is constantly being updated.
Right now I'm using the BlockingScheduler paired with my own condition to stop the job (stop job if processed 1k data etc.), I was wondering if APScheduler supports this "only 1 job at the same time and stop old one before new one" behavior natively
I've read the docs but I think the closest is still the default behavior which equals max_instances=1, this just prevents new jobs firing before the old job finishes, which is not what I'm looking for.
Any help is appreciated. Thanks!
After further research I came to a conclusion that this is not supported natively in APScheduler, but by inspired by
Get number of active instances for BackgroundScheduler jobs
, I modified the answer into a working way of detecting the number of current running instances of the same job, so when you have a infinite loop/long task executing, and you want the new instance to replace the old instance, you can add something like
if(scheduler._executors['default']._instances['set_an_id_you_like'] > 1):
# if multiple instances break loop/return
return
and this is what should look like when you start:
scheduler = BlockingScheduler(timezone='Asia/Taipei')
scheduler.add_job(main,'cron', minute='*/30', max_instances=3, next_run_time=datetime.now(),\
id='set_an_id_you_like')
scheduler.start()
but like the answer in the link, please refrain from doing this if someday there's a native way to do this, currently I'm using APScheduler 3.10
This method at least doesn't rely on calculating time.now() or datetime.datetime.now() in every iteration to check if the time has passed compared when the loop started. In my case since my job runs every 30 minutes, I didn't want to calculate deltatime so this is what I went for, hope this hacky method helped someone that googled for a few days to come here.

Using Optaplanner for long trip planning of a fleet of vehicles in a Vehicle Routing Problem (VRP)

I am applying the VRP example of optaplanner with time windows and I get feasible solutions whenever I define time windows in a range of 24 hours (00:00 to 23:59). But I am needing:
Manage long trips, where I know that the duration between leaving the depot to the first visit, or durations between visits, will be more than 24 hours. So currently it does not give me workable solutions, because the TW format is in 24 hour format. It happens that when applying the scoring rule "arrivalAfterDueTime", always the "arrivalTime" is higher than the "dueTime", because the "dueTime" is in a range of (00:00 to 23:59) and the "arrivalTime" is the next day.
I have thought that I should take each TW of each Customer and add more TW to it, one for each day that is planned.
Example, if I am planning a trip for 3 days, then I would have 3 time windows in each Customer. Something like this: if Customer 1 is available from [08:00-10:00], then say it will also be available from [32:00-34:00] and [56:00-58:00] which are the equivalent of the same TW for the following days.
Likewise I handle the times with long, converted to milliseconds.
I don't know if this is the right way, my consultation would be more about some ideas to approach this constraint, maybe you have a similar problematic and any idea for me would be very appreciated.
Sorry for the wording, I am a Spanish speaker. Thank you.
Without having checked the example, handing multiple days shouldn't be complicated. It all depends on how you model your time variable.
For example, you could:
model the time stamps as a long value denoted as seconds since epoch. This is how most of the examples are model if I remember correctly. Note that this is not very human-readable, but is the fastest to compute with
you could use a time data type, e.g. LocalTime, this is a human-readable time format but will work in the 24-hour range and will be slower than using a primitive data type
you could use a date time data tpe, e.g LocalDateTime, this is also human-readable and will work in any time range and will also be slower than using a primitive data type.
I would strongly encourage to not simply map the current day or current hour to a zero value and start counting from there. So, in your example you denote the times as [32:00-34:00]. This makes it appear as you are using the current day midnight as the 0th hour and start counting from there. While you can do this it will affect debugging and maintainability of your code. That is just my general advice, you don't have to follow it.
What I would advise is to have your own domain models and map them to Optaplanner models where you use a long value for any time stamp that is denoted as seconds since epoch.

Collect statistics on current traffic with Bro

I want to collect statistics on traffic every 10 seconds and the only tool that I found is connection_state_remove event,
event connection_state_remove(c: connection)
{
SumStats::observe( "traffic", [$str="all"] [$num=c$orig$num_bytes_ip] );
}
how to deal with those connections that did not removed by the end of this period. How to get statistics from them?
The events you're processing are independent of the time interval at which the SumStats framework reports statistics. First, you need to define what exactly are the statistics you care about — for example, you may want to count the number of connections for which Bro completes processing in a given time interval. Second, you need to define the time interval (in your case, 10 seconds) and how to process the statistical observations in the SumStats framework. This latter part is missing in your snippet: you're only making an observation but not telling the framework what to do with it.
The examples in the SumStats documentation are very close to what you're looking for.

Triggering some code on every nth iteration of an NSTimer tick

I'm relatively new to coding, and wondering if there's a conventional way to have some code execute on every nth iteration of a loop (in this case, an NSTimer ticking).
I'm using a CADisplayLink and it updates however many times per second, 40, 50, whatever. If I want to execute some code on every, say, 500 of those loops, is there a standard way to do so? I assume I could put something together with the modulo operator and an integer, but is there a better / more normalized way that a new coder should know?
Extra clarity (though I'm sure this is a fairly common thing to do..): I have a timer that ticks 60 times per second, but I only want to do something with every 10th iteration. I already know that I can use a modulo and an integer to do this, but I want to know if there's any other convention for handling a situation like this.
Thanks in advance!
Establish a dedicated timer for the right interval.
Regardless of whether you're using NSTimer or CADisplayLink, timer calls can be coalesced and offset if they take too long. If you have a display link that takes 20 frames to run, it only gets called thrice every second (given the refresh interval is 60 frames per second). And if you have a timer set to run every second that at one instance takes a bit more than two and a half seconds to run, it will have "ate" its next iteration and will run the next iteration half a second too late.
Because of this, your timer can get out of sync if you only count timer calls. To do something repeatedly on an interval, having a timer set to that interval is the absolute best approximation.
Having a second timer like this is not a performance problem unless you do very many timers, in which case you should standardize on one tick timer and have events scheduled for specific points in time (which still isn't the same as counting previous iterations).

DOS batch: Advance system clock N number of days?

I need some pointer crafting an MS-DOS batch "function" to advance the system calendar N number of days from the current one. Is there a more machine-friendly command, or am I stuck with DATE and some Franken-hack parsing of it?
On one of my favorite batch sites on the net Rob van der Woude's Scripting Pages you can find in the examples section a script called DateAdd.bat. It will calculate and print a new date based on a given date and offset.
It should be fairly easy to change the script to your needs or use it along with your own script. Get back to us if you need further help with that.
If you're truly using MS-DOS rather than the more advanced cmd.exe, your options are very limited since the variable manipulation was pretty bad.
I do remember needing something similar in a previous life. From memory, rather than trying to screw around with date calculations, we simply ran a loop (one iteration for each day) and, inside the loop, set the time to 23:59 then wait for five seconds or so. Unfortunately, I think that pre-dated ping so we couldn't even use the sleep trick - we had to run a lengthy goto loop to be certain.
That way, DOS itself figured out whether "tomorrow" was the 31st of September or 1st of October.
In the end, it became too much trouble so I would suggest you do what we finished up doing. Grab yourself a copy of Turbo C from Borland's (or InPrise or Enchilada or whatever they're called nowadays - they'll always be Borland to me) museum site and write a quick little C program to do it for you .