I use several stopwatches in my application. They are all created together, but only some of them have actually run (due to exceptions earlier in the code or other things).
After my application has run, I'm creating my report using those stopwatches. For instance, I'm doing the following:
Stopwatch subStopwatch = Stopwatch.createUnstarted();
Stopwatch mainStopwatch = Stopwatch.createStarted();
try {
// do something 1
subStopwatch.start();
// do something 2
subStopwatch.stop();
} finally {
mainStopwatch.stop();
System.out.printf("Total run time: %s%n", mainStopwatch);
if (!subStopwatch.isRunning()) {
System.out.printf(" including sub run time: %s%n", subStopwatch);
}
}
The problem in this code is that if something happens in "do something 1" (return, exception), subStopwatch will be printed anyways.
The following solutions work:
- Using a boolean to indicate I started the stopwatch.
- Using a stopwatch more locally and using a report mechanism that contains the information I'm looking for.
But the main question remains: can I know that a stopwatch has run using Stopwatch only.
You can check the elapsed time on the stopwatch:
if (subStopwatch.elapsed(TimeUnit.NANOSECONDS) > 0) {
// it ran
}
Related
I'm trying to implement retry logic so that if my request fails due to some technical problem (timeout, connection reset etc.) or error code 4xx|5xx, script tries to re-submit it couple of times with some pause
My code looks like this
scenario("my_simulation")
.repeat(2) {
tryMax(5, "retryLoopIndex") {
//pause(session => computePause(session("retryLoopIndex").as[Int]))
println(LocalDateTime.now() + """Before sleep""")
pause(5.seconds)
println(LocalDateTime.now() + """After sleep""")
exec(http("get_eps_internal")
.get("/500")
.headers(headers_0)
.requestTimeout(GlobalRequestTimeout)
.check(status.is(200))
)
}
}
I have 2 problems here:
it seems like pause "happens" only once when scenario gets initialized
it pauses for couple milliseconds, not 5 seconds as I would expect
From the logs
2022-02-04T08:23:06.404 Before sleep
2022-02-04T08:23:06.408 After sleep
Ho can I add pause before each retry?
The way you are calling the println() is not correct. In fact, println() called once and before starting the load test. If you want to call during the test you need to do this:
.exec { session =>
println(LocalDateTime.now() + """Before sleep""")
session
}
Another point is that you call actions without a "dot" and it isn't a right way
... {
pause(5.seconds)
exec(http("get_eps_internal")
... }
You need do this:
... {
pause(5.seconds)
.exec(http("get_eps_internal")
... }
I am very confused about this. I request you to clarify the concept.
Consider the following scenarios:
Case 1:
int number = 0;
void calculate() {
number = number + 2;
print(number);
}
I know this works just fine. "2" will be printed on the terminal.
But why shouldn't I use async-await here, like this:
int number = 0;
void calculate() async {
void addition() async {
number = number + 2;
}
await addition();
print(number);
}
This seems logical to me, since print(number) should wait for number = number + 2 to finish. Why isn't this necessary? How does dart know which operation to execute first?
How is it ensured that print(number) isn't executed before number = number + 2 and "0" is printed on the terminal?
Does the sequence in which we write these operations in the function matter?
Case 2:
Consider the case where I am interacting with SQFLite database and values fetched depend on each other.
Note: number1, number2, number3 will still have values before the following function is called.
void getValues() async {
void calculate1() {
number1 = await db.getNumber1(10);
}
void calculate2() {
number2 = await db.getNumber2(number1);
}
await calculate1().then((_) async {
await calculate2().then((_) async {
number3 = await db.getNumber3(number2);
});
});
}
I have a lot of these types of functions in my app and I am doing this everywhere.
I am kind of paranoid, thinking if old values of number1and number2 are taken as a parameter in getNumber2() and getNumber3() respectively, then I'll be doomed.
async/await are just syntax sugar for the underlying Future framework. 95% of the time, they will suffice, and are preferred by the style guide.
One exception is that you may have multiple futures that you want to wait until all are complete in parallel. In that case, you'll need to use Future.wait([future1, future2, future3]), which cannot be expressed using await.
Dart is executed line by line. So when the function is called calculation will be done first then it will be printed. So you will always get 2 printed
You can see it like there is one main thread in general which is the UI thread. Any operations you are writing in this thread will be performed line by line and after completely executing one line it will move to next line.
Now suppose you have something which you know that it will take time to be computed or fully executed with either a result or error. If you will write this in the main UI thread (synchronous thread) that means you're stopping the UI of the app, which in turn makes the app to crash(Application Not Responding Error) as the operating system feels that the app has frozen but as you know this is happening because of the compute you are running in the UI thread which is taking time and the UI is waiting for it to be completely executed.
So to overcome this issue we use Asynchronous methods to compute the time taking computations like getting some data from a database which will return a value or error in "future". The main UI thread doesn't waits for the asynchronous threads. If you don't have anything to show to the user until any asynchronous task is completed you place the loading indicators for the time being.
Hope this helps!
I'm trying to write an Eclipse plugin which gets all current running LaunchConfigurations (run- and debugmode ones) and terminates them from the back (see img. 1.1).
I know, that there is a terminate() method within the class ILaunchConfiguration, but I don't think that this is what I'm looking for.
[img. 1.1]
here is an example of LaunchConfigurations (the second and the third are in debugmode), that I want to terminate from last to first.
Any help is appreciated as always!
Get the list of current launches from the launch manager and terminate the active processes.
Something like:
ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();
ILaunch [] launches = manager.getLaunches();
for (ILaunch launch : launches) {
IProcess [] processes = launch.getProcesses();
for (IProcess process : processes) {
if (process.canTerminate()) {
process.terminate();
}
}
}
I don't know if any of you has already been playing with the recently available API for spotify but there is something that is bugging me.
Once you get passed the -(void)sessionDidLoginSuccessfully:(SPSession *)aSession callback, pretty much no information is the SPSession object.
But a bit of code inspection on the CocoaLibSpotify this seems actually normal, the data is retrieved later on.
The problem is that, it seems like of this information is actually never retrieved. I've followed a similar behavior as their "Guess the Intro" example and if I do:
- (void)sessionDidLoginSuccessfully:(SPSession *)aSession
{
// trying to fetch another piece of info about the user
userTopList = [[SPToplist toplistForCurrentUserInSession:session] retain];
[self waitForReadiness];
}
- (void)waitForReadiness
{
// Event after 10 seconds userPlaylists is still nil
if (![[[SPSession sharedSession] userPlaylists] isLoaded])
{
playlistsAttempts++;
if (playlistsAttempts < 10)
{
[self performSelector:_cmd withObject:nil afterDelay:1.0];
return;
}
}
// However, after only 1 second, userTopList is fetched
if (userTopList.isLoaded )
{ /* do stuff */ }
}
Basically the userTopList is correctly set after less than a second while the main session userPlaylists keeps being nil.
On the given example, the same thing is happening.
So I'm starting to think that the lib is just not quite there yet, but I would gladly take your inputs.
I was having the same problem and found that the following patch sorted my problem:
https://github.com/spotify/cocoalibspotify/commit/2c9b85e306a8849675e5b30169481d82dbeb34f5
Hope this helps.
-Dx
From within an Eclipse plugin, I'd like to run an Ant build script. I also want to display the Ant output to the user, by displaying it in an Eclipse console. Finally, I also want to wait for the Ant build to be finished, and capture the result: did the build succeed or fail?
I found three ways to run an Ant script from eclipse:
Instantiate an org.eclipse.ant.core.AntRunner, call some setters and call run() or run(IProgressMonitor). The result is either normal termination (indicating success), or a CoreException with an IStatus containing a BuildException (indicating failure), or else something else went wrong. However, I don't see the Ant output anywhere.
Instantiate an org.eclipse.ant.core.AntRunner and call run(Object), passing a String[] containing the command line arguments. The result is either normal termination (indication success), or an InvocationTargetException (indicating failure), or else something else went wrong. The Ant output is sent to Eclipse's stdout, it seems; it is not visible in Eclipse itself.
Call DebugPlugin.getDefault().getLaunchManager(), then on that call getLaunchConfigurationType(IAntLaunchConfigurationConstants.ID_ANT_BUILDER_LAUNCH_CONFIGURATION_TYPE), then on that set attribute "org.eclipse.ui.externaltools.ATTR_LOCATION" to the build file name (and attribute DebugPlugin.ATTR_CAPTURE_OUTPUT to true) and finally call launch(). The Ant output is shown in an Eclipse console, but I have no idea how to capture the build result (success/failure) in my code. Or how to wait for termination of the launch, even.
Is there any way to have both console output and capture the result?
Edit 05/16/2016 #Lii alerted me to the fact that any output between the ILaunchConfigurationWorkingCopy#launch call and when the IStreamListener is appended will be lost. He made a contribution to this answer here.
Original Answer
I realize this is an old post, but I was able to do exactly what you want in one of my plugins. If it doesn't help you at this point, maybe it will help someone else. I originally did this in 3.2, but it has been updated for 3.6 API changes...
// show the console
final IWorkbenchPage activePage = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow()
.getActivePage();
activePage.showView(IConsoleConstants.ID_CONSOLE_VIEW);
// let launch manager handle ant script so output is directed to Console view
final ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();
ILaunchConfigurationType type = manager.getLaunchConfigurationType(IAntLaunchConstants.ID_ANT_LAUNCH_CONFIGURATION_TYPE);
final ILaunchConfigurationWorkingCopy workingCopy = type.newInstance(null, [*** GIVE YOUR LAUNCHER A NAME ***]);
workingCopy.setAttribute(ILaunchManager.ATTR_PRIVATE, true);
workingCopy.setAttribute(IExternalToolConstants.ATTR_LOCATION, [*** PATH TO ANT SCRIPT HERE ***]);
final ILaunch launch = workingCopy.launch(ILaunchManager.RUN_MODE, null);
// make sure the build doesnt fail
final boolean[] buildSucceeded = new boolean[] { true };
((AntProcess) launch.getProcesses()[0]).getStreamsProxy()
.getErrorStreamMonitor()
.addListener(new IStreamListener() {
#Override
public void streamAppended(String text, IStreamMonitor monitor) {
if (text.indexOf("BUILD FAILED") > -1) {
buildSucceeded[0] = false;
}
}
});
// wait for the launch (ant build) to complete
manager.addLaunchListener(new ILaunchesListener2() {
public void launchesTerminated(ILaunch[] launches) {
boolean patchSuccess = false;
try {
if (!buildSucceeded[0]) {
throw new Exception("Build FAILED!");
}
for (int i = 0; i < launches.length; i++) {
if (launches[i].equals(launch)
&& buildSucceeded[0]
&& !((IProgressMonitor) launches[i].getProcesses()[0]).isCanceled()) {
[*** DO YOUR THING... ***]
break;
}
}
} catch (Exception e) {
[*** DO YOUR THING... ***]
} finally {
// get rid of this listener
manager.removeLaunchListener(this);
[*** DO YOUR THING... ***]
}
}
public void launchesAdded(ILaunch[] launches) {
}
public void launchesChanged(ILaunch[] launches) {
}
public void launchesRemoved(ILaunch[] launches) {
}
});
I'd like to add one thing to happytime harry's answer.
Sometimes the first writes to the stream happens before the stream listener is added. Then streamAppended on the listener is never called for those writes so output is lost.
See for example this bug. I think happytime harry's solution might have this problem. I myself registered my stream listener in ILaunchListener.launchChanged and this happened 4/5 times.
If one wants to be sure to get all the output from a stream then the IStreamMonitor.getContents method can be used to fetch the output that happened before the listener got added.
The following is an attempt on a utility method that handles this. It is based on the code in ProcessConsole.
/**
* Adds listener to monitor, and calls listener with any content monitor already has.
* NOTE: This methods synchronises on monitor while listener is called. Listener may
* not wait on any thread that waits for monitors monitor, what would result in dead-lock.
*/
public static void addAndNotifyStreamListener(IStreamMonitor monitor, IStreamListener listener) {
// Synchronise on monitor to prevent writes to stream while we are adding listener.
// It's weird to synchronise on monitor because that's a shared object, but that's
// what ProcessConsole does.
synchronized (monitor) {
String contents = monitor.getContents();
if (!contents.isEmpty()) {
// Call to unknown code while synchronising on monitor. This is dead-lock prone!
// Listener must not wait for other threads that are waiting in line to
// synchronise on monitor.
listener.streamAppended(contents, monitor);
}
monitor.addListener(listener);
}
}
PS: There is some weird stuff going on in ProcessConsole.java. Why is the content buffering switched of from the ProcessConsole.StreamListener constructor?! If the ProcessConsole.StreamListener runs before this one maybe this solution doesn't work.