consitant interval timer (runnable results not sufficient) - timer

We want to code a very accurate and consistent timer interval (100ms) to generate a periodic light pattern with the phone tourchlight.
Currently we use a runnable function, but this shows a lot of deviation.
If we measure the response with a photodiode we perceive deviations between 80 and even 150ms!
Is this error caused by the runnable function or the execution of the enable/disable of the Tourch function.

Below you can find the runnable that we used to trigger the phone tourchlight. The on/off period should be 100ms but is inconsistant variation of lenght and variation between on/off period. could this have to do with the camera service?
private final Runnable mRunnable = new Runnable() {
public void run() {
if (mActive) {
if (mSwap) {
mSwap = false;
mHander.postDelayed(mRunnable, 100);
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
} else {
mSwap = true;
mHander.postDelayed(mRunnable, 100);
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
}
}
}
};
Please let us know if you need more information

Related

Flink DataStream sort program does not output

I have written a small test case code in Flink to sort a datastream. The code is as follows:
public enum StreamSortTest {
;
public static class MyProcessWindowFunction extends ProcessWindowFunction<Long,Long,Integer, TimeWindow> {
#Override
public void process(Integer key, Context ctx, Iterable<Long> input, Collector<Long> out) {
List<Long> sortedList = new ArrayList<>();
for(Long i: input){
sortedList.add(i);
}
Collections.sort(sortedList);
sortedList.forEach(l -> out.collect(l));
}
}
public static void main(final String[] args) throws Exception {
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(2);
env.getConfig().setExecutionMode(ExecutionMode.PIPELINED);
DataStream<Long> probeSource = env.fromSequence(1, 500).setParallelism(2);
// range partition the stream into two parts based on data value
DataStream<Long> sortOutput =
probeSource
.keyBy(x->{
if(x<250){
return 1;
} else {
return 2;
}
})
.window(TumblingProcessingTimeWindows.of(Time.seconds(20)))
.process(new MyProcessWindowFunction())
;
sortOutput.print();
System.out.println(env.getExecutionPlan());
env.executeAsync();
}
}
However, the code just outputs the execution plan and a few other lines. But it doesn't output the actual sorted numbers. What am I doing wrong?
The main problem I can see is that You are using ProcessingTime based window with very short input data, which surely will be processed in time shorter than 20 seconds. While Flink is able to detect end of input(in case of stream from file or sequence as in Your case) and generate Long.Max watermark, which will close all open event time based windows and fire all event time based timers. It doesn't do the same thing for ProcessingTime based computations, so in Your case You need to assert Yourself that Flink will actually work long enough so that Your window is closed or refer to custom trigger/different time characteristic.
One other thing I am not sure about since I never used it that much is if You should use executeAsync for local execution, since that's basically meant for situations when You don't want to wait for the result of the job according to the docs here.

Is there a method only retrieve location coordinates when there is a change

Following methods are used to start and stop location tracking using my App to poll the location continuously almost every minute. I would like to capture the location only when there is a change in coordinates. I'm wondering there is any method that would do comparison and retrieve location when there is a change.
I have tried to manually compare the coordinates which is making the requests slow down. Please advise.
public void stopTracking() {
if (time != null) {
time.cancel();
}
time = null;
LocationManager.getLocationManager().setLocationListener(null);
}
public void startTracking() {
if (time != null) {
stopTracking();
}
if (Preferences.get("LocationTracking", true)) {
long delay = Server.instance.getLoctionPollingIntervalMillis();
LocationManager.getLocationManager().setLocationListener(this,
new LocationRequest(LocationRequest.PRIORITY_LOW_ACCUARCY, delay));
time = new Timer();
time.schedule(new TimerTask() {
#Override
public void run() {
if (lastLocation != null) {
double lat = (double) lastLocation.getLatitude();
double lot = (double) lastLocation.getLongitude();
Server.instance.updateLocationInServer(lat, lot, System.currentTimeMillis(), true);
}
}
}, 30000, delay);
}
}
Remove the timer code and write the server update in the LocationRequest class which is invoked by the listener. I'd also suggest adding an update threshold as some implementations can update you on a very high frequency and on movement that's very fine.

Changing timer interval dynamically in Java 1.4

I have a timer task as shown below:
long timerSec = 5000;
TimerTask task1 = new TimerTask()
{
public void run()
{
//Some code...
System.out.println("Timer task...");
}
};
And a timer object as shown below:
Timer readFileTimer = new Timer();
I scheduled a task with 5 secs period between two successive task executions.
readFileTimer.scheduleAtFixedRate(task1, 0, timerSec);
Below line of code assigns new time period. I want to change the time period from 5 secs to n-secs (lets say 10 secs w.r.t. timerSec value).
timerSec = CalculateTimeForUpgrade(); //Get new timer interval period.
I tried below code, but didn't get the expected result.
readFileTimer.scheduleAtFixedRate(task1, 0, timerSec);
Please help. Thanks in advance.
Instead of starting the task at a fixed interval from the beginning, reschedule the task every time you finish it.
Something like this:
final Timer readFileTimer = new Timer();
readFileTimer.schedule(new MyTimerTask(), 0);
.......
private class MyTimerTask extends TimerTask() {
#Override
public void run() {
// Some code...
System.out.println("Timer task...");
if (readFileTimer!=null)
readFileTimer.schedule(new MyTimerTask(), CalculateTimeForUpgrade());
}
}

Windows Form UI Update issue with Task in C#

We are working on a windows application which caters to an engineering calculation which are essentially very long running. So we are basically trying to keep the calculation module separate and working in a separate worker thread and pass it an Action delegate in method signature which will be invoked to report the calculation progress in the UI. The delegate handler declared in the UI will be updating the UI. We found that while a huge loop is running in the calculation, the UI is not showing the periodic progress and only displaying the final result. If a Thread Sleep for 1 millisecond is introduced in the calculation loop, the UI is getting updated correctly. This is not expected behavior as we are executing the calculation using a separate Task and updating the UI using BeginInvoke calls.
I have created a simple application to demonstrate our approach and code so that it is easier to understand. It is obvious that we are missing something very simple but cannot quite pin it down. Will appreciate any insights.
Thanks for reading.
private void cmdStart_Click(object sender, EventArgs e)
{
txtResultDIsplay.Text = "";
var maxIterations = long.Parse(txtIterationNo.Text.Trim());
var ui = TaskScheduler.FromCurrentSynchronizationContext();
Task<double> calculationTask = Task.Factory.StartNew<double>(
() => SumRootN(maxIterations, UpdateProgress));
var handleResultTask = calculationTask.ContinueWith((t) => DisplayResult(t),
CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, ui);
}
private void DisplayResult(Task<double> calculationTask)
{
txtResultDIsplay.Text = "Final Calculation Result : " + calculationTask.Result.ToString();
}
private void UpdateProgress(string msg)
{
this.BeginInvoke((MethodInvoker)delegate
{
txtResultDIsplay.Text = msg;
});
}
public double SumRootN(long maxIterations, Action<string> progressUpdateDelegate)
{
int root = 20;
double result = 0;
for (long i = 1; i < maxIterations; i++)
{
Thread.Sleep(1);
result += Math.Exp(Math.Log(i) / root);
progressUpdateDelegate(result.ToString("0.00000"));
}
return result;
}
It is possible you are flooding the UI thread with your progress updates. You need to find a way to prevent lots of updates occurring.
We can solve the problem using tasks!
Task progressTask = null;
private void UpdateProgress(string msg)
{
//only schedule work if the task if not running
if(progressTask == null || progressTask.IsCompleted) //updates will end if there is an exception!
{
//Create a task representing the update
progressTask = Task.Factory.FromAsync<object>(BeginInvoke(new Action(() => txtResultDIsplay.Text = msg)), this.EndInvoke)
.ContinueWith(() => System.Threading.Thread.Sleep(100)); //add a sleep on the end
}
}
Note that locking will not do here as you want to skip the update if there is already an update occurring.

Threading.Timer stack overflow

Hy, I just wanted to find out how to implement a loop that takes around 80 to 120ms (mostly 80ms) to execute. The loop has to execute for about 30 minutes... basically it is a SURF matching algorithm.
Currently I am using a System.Threading.Timer to create a timer that executes after every 90ms, but the problem is that since the computation time is variable, so after some time the stack overflows and the program closes.
I'm using WPF to create the GUI.
Is there a better way to implement such a loop using threading? Any help would be much appreciated! Thanks in advance.
//initialization
private System.Threading.Timer Visual_AR1;
Visual_AR1 = new System.Threading.Timer(new TimerCallback(Video_AR1), null, 0, 90);
private void Video_AR1(object state)
{
lock (this)
{
// SURF matching
modelImage_AR1 = new Image<Gray, byte>(droneControl_AR1.BitmapImage).Resize(1.8, INTER.CV_INTER_NN);
map_image_d1 = DrawMatches_gpu.GPU_0(wayx, modelImage_AR1, observedImage, pgpuObservedKeyPoints_imp, pgpuObservedDescriptors_imp, out matchTime_0, out pX1, out pY1);
Dispatcher.BeginInvoke((Action)delegate()
{
label4.Content = "Time Taken by GPU_0 : " + matchTime_0.ToString();
});
mask_selector_d1();
}
}
is this a viable solution ?
private Thread threadTask = null;
private void threadTask_Start()
{
if (threadTask == null) {
threadTask = new Thread(SURF);
threadTask.Start();
}
}
private void SURF()
{
while(true)
{
lock (this)
{
// SURF matching
modelImage_AR1 = new Image<Gray, byte>(droneControl_AR1.BitmapImage).Resize(1.8, INTER.CV_INTER_NN);
map_image_d1 = DrawMatches_gpu.GPU_0(wayx, modelImage_AR1, observedImage, pgpuObservedKeyPoints_imp, pgpuObservedDescriptors_imp, out matchTime_0, out pX1, out pY1);
Dispatcher.BeginInvoke((Action)delegate()
{
label4.Content = "Time Taken by GPU_0 : " + matchTime_0.ToString();
});
mask_selector_d1();
}
thread.sleep(40);
}
}
Instead of making the timer tick perform the work, make the timer tick queue up a job and have something else (presumably threads from the thread pool) consume the jobs. You can use a semaphore to throttle the number of jobs running simultaneously and you can examine the state of the queue to avoid this sort of over-commit problem.

Resources