Best way to simulate a server which randomly sends alarms - java

Here's what I need to do:
I need to simulate a server, which sends alarms at random intervals, i.e. after 2 secs, then after 4, after 10 but always within some sort of range.
What is the best way to achieve this?
Here's my fist idea:
1.) Choose a random value between 0 and 10.
2.) Sleep for that amount of time
3.) Send an alarm to the client
4.) Repeat forever (i.e. while (true))

Your idea doesn't sound so bad. Of course, you could go a more sophisticated path using timers and signals, but it depends on the requirements and using simply sleep() is maybe the fastest and easiest way for your purposes. Go for it :)

For range 4-10 seconds, choose a random value 0..6 (10-4), add 4, sleep this amount of seconds (or get current time, add the value, and loop with a short sleep rechecking the time), send alarm, rinse, repeat.

Related

Timeouts for multiple clients in Java

I have one Server and multiple clients. With some period, clients sends an alive packet to Server. (At this moment, Server doesn't respond alive packets). The period may change device to device and configurable at runtime, for both Server and Clients. I want to generate an alert when one or more clients doesn't send the alive packet. (One packet or two in row etc.). This aliveness is used other parts of application so the quicker notice is the better. I came up some ideas but I couldn't select one.
Create a task that checks every clients last alive packet timestamps with current time and generate alert or alerts. Call this method in some period which should be smaller than minimum client-period.
Actually that seems better to me, however this way unnecessarily I check some clients alive. (Ex: If clients period are change 1-5 minute, task should be run in every minute at least, so I check all clients above 2 minute period is redundant). Also if the minimum of client periods is decrease, I should decrease the tasks period also.
Create a task for each clients, and check the last alive packet timestamps with current time, sleep for one client's period time.
In this way, if clients number goes very high, there will be dozens of task. Since they will sleep most of the time, I still doubt this is more elegant.
Is there any idiom or pattern for this kind of situation? I think watchdog kind implementation is suite well, however I didn't see something like in Java.
Approach 2 is not very useful as it is vague idea to write 100 task for 100 clients.
Approach 1 can be optimized if you use average client-period instead of minimum.
It depends on your needs.
Is it critical if alert is generated few seconds later (or earlier) than it should be?
If not then maybe it's worth grouping clients with nearby heartbeat intervals and run the check against not a single client but the group of clients? This will allow to decrease number of tasks (100 -> 10) and increase number of clients handled by single task (1 -> 10).
First approach is fine.
Only thing I can suggest you is that create an independent service to do this control. If you set this task as a thread in your server, it wouldn't be that manageable. Imagine your control thread is broken, killed etc, how would you notice? So, build an independent OS service, another java program, to check last alive timestamps periodically.
In this way you can easily modify and restart your service and see its logs separately. According to its importance, you may even built a "watchdog of watchdog" service too.

Make a thread generate fixed number of requests per second

I am doing calculations in milliseconds and I really do not want my thread to spend more time doing time calculations rather the job it is assigned to do. However I want to implement something that:
1- It should not generate more than n requests per second
2- If it has generated less, it should start at zero for the next second(obviously :D)
I am trying to do some performance benchmarking where my goal is to give all cpu to only processing and not time computations after every request. Roughly, I am processing
08:36 - 171299
08:37 - 170970
08:38 - 163763
I want to make sure I do not make more than 160000 requests per minute here. How to acheive that is the problem.
Thanks in advance!
You can combine ScheduledExecutorService to run some code every second and this answer to set timeout on that code. In the end, your runnable that should have 1-second timeout should generate up to n requests, and if it times out, it will start in next second with new context.

Mimic spinning wheel in code?

I've been searching a lot but I just can see to find any examples of what I'm looking for.
Basically what I want to do is mimic the functionality of spinning a wheel like on wheel of fortune but with no graphics, just code. So what would happen is I'd start the function and then it'd output 1 number per second, then after a certain amount of time it'll start spitting out 1 number every 3 seconds, then every 5 seconds, etc.. until it finally stops and picks 1 number. Kind of like how when you spin a bottle it gradually comes to a stop.
At first I thought I could achieve this using ScheduledExecutors but its really tricky seeing as I have to calculated when to stop the previous task before I start the next one.
Does anyone have a more simple solution?

Java time based execution

I want to do the following. I count the occurence of an event in my program. What I wish to achieve is that at the end of every hour (Of the MST i.e the time zone where I am in) the count be recorded in the database for that hour. All I need is a code snippet which would execute at the end of every hour. Note that I don't want the thread to sleep because I also need to update counts when events occur.
You can implement a TimerTask so search for that. Or if you can use Quartz. Google search should be your first stop.
In Java, there's no way to ensure that a Runnable gets executed exactly at a given time.
You can only schedule a Runnable to be executed at intervals of approximately a given time. If that's enough for you, then a java.util.Timer or Executors.newSingleThreadScheduledExecutor() is good enough. You only need to put your counter in a thread-safe and atomic variable (AtomicInteger may be enough, depending on the numbers you are expecting to have).
If you want to have extreme precision, then you'd better modify your event handler, so that, before recording the event, it checks in which hour it is and, depending on that, it uses a different "slot" inside a queue. Finally, your scheduled task would gather old queue slots, removing them from the queue and storing to database. (I think this is excessive, but it's up to you).

Alarm clock in Java

I want to make a program that will make a pop-up appear at a certain time in the future, eg. 5:00 tonight. Basically, the program is a reminder/notification system for appointments, meetings, etc.
My first instinct was to create a sort of "Clock Listener" that would check the computer's time every minute or so and see if currentTime == alarmTime. However, I don't know if this takes up too much resources or if it is just a bad practice to have your program constantly doing things like that. Also, for the alarm to be accurate, I think it would need to check every second, rather than every minute (since if it isn't checking the seconds and will go off at 5:00:xx, it could go off at 5:00:59, which may be too late for some people's liking). Is checking the clock every second too much?
My second thought was when the program starts running, calculate how long it is until the alarm is set to go off (say, in five hours). Then, wait five hours, and then sound the alarm. But then I thought, though unlikely, it would be possible for the user to change the computer's time, and then the alarm would go off at the wrong time. So this doesn't really work.
I've seen some solutions that use threads, but I'm not familiar with those yet, so I'd rather not use them.
I'm leaning towards the first solution, but I want to make sure it's efficient and won't slow down other programs. Perhaps I'm overthinking it and checking the clock is a trivial operation, but I just wanted to make sure I'm not doing anything wrong.
The sleep solution is very straightforward, but using java.util.Timer is not much harder, and gives you a clear way to extend your utility for multiple alarms, etc. Assuming you are going to use Swing to display the notification, note that your TimerTask will need to perform some of its work on the Swing event thread. SwingUtilities.invokeAndWait(...) will help you with that.
The first solution is OK. Waking up, checking the time, and going back to sleep should not be a problem at all. You can check every second if you want, but if you only need 1-minute resolution perhaps it is enough to check e.g. every 30 seconds.
The second approach has the problem you have outlined already. If you just go to sleep for the time remaining, and the user changes the time (or the time is changed by some other means, e.g. synchronisation with a time server), the alarm would go off at the wrong time. You could avoid this if you could register some sort of hook so that your program is called back when the system time changes, but you cannot easily do this in Java.

Categories