C#/MonoTouch implement a StopWatch showing time on a label dynamically - xamarin.ios

Is it possible to implement a stopwatch showing stopwatch values changing on label as watch is running.
I have added stopwatch using following code
Stopwatch stopwatch = new Stopwatch();
// Begin timing
stopwatch.Start();
// Stop timing
stopwatch.Stop();
How should i show time running on a label ????

Use a Timer instead of a Stopwatch.
// create a timer that fires every 10 ms
Timer aTimer = new Timer(10);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Enabled = true;
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
// update your label here
}

Related

How to use properly Timer with thread in Xamarin?

I would like to use a timer , to execute a time, pause and stop.
has spent several days that i search how to use in the best way a timer because, as you know, it does not exist a timer directly unless to create it.
so, I followed these informations by creating a timer, using a timespan, timercallback and stopwatch :
Timer doesn't contain in System.Threading at Xamarin.Forms
https://developer.xamarin.com/api/namespace/System.Timers/
https://developer.xamarin.com/api/type/System.Diagnostics.Stopwatch/
I think that stopwatch is the best. And with several manupulations, i have what i wanted, but the problem is that the time runs out that every time I press the run button, when I should press once on the button.
With a Thread too, I had done but it dis not change anything. I do not know why it do that.
And it is the same with a Datetime, I would like that the time of the Datetime continues to run while i did not press another button to stop it.
If someone would have an idea avout it, really thank you in advance.
As I said, i think i have what i would. But I need to press just one time the button to run the chronometer instead of press it everytime with an incrementation of time milliseconds by milliseconds.
So, here is my chronoTimer.cs for that :
class TimerExpand
{
public int counter = 0;
public System.Threading.Timer threadTimer;
}
public static void Temps()
{
TimerExpand t_expand = new TimerExpand();
TimerCallback timerDelegate = new TimerCallback(GetTime);
System.Threading.Timer timer = new System.Threading.Timer(timerDelegate, t_expand, 0, 1000);
t_expand.threadTimer = timer;
}
public static void GetTime(object etat)
{
TimerExpand t_expand = (TimerExpand) etat;
t_expand.counter++;
}
private DateTime actualDate;
public static Stopwatch sw;
And then on my buttonTimer_OnClicked method :
actualDate = DateTime.Now;
sw = new Stopwatch();
sw.Start();
labelChrono.Text = string.Format("{0:00}:{1:00}:{2:00}:{3:00}", sw.Elapsed.Hours, sw.Elapsed.Minutes, sw.Elapsed.Seconds,
sw.Elapsed.Milliseconds);
labelDate.Text = DateTime.Now.ToString();
Temps();
}

How to use android timer

I am developing an android app.In my main activity i have two layouts. 1st relative Layout which have visibility gone and after that one LinerLayout which is visible.In my activity class,I want to set the timer so that after 3 second my LinerLayout should be gone and RelativeLayout should be visible.How to do that ?
you can use java.util.Timer to achiever this.
For repeating task, use following:
new Timer().scheduleAtFixedRate(task, after, interval);
For a single run of a task, use following:
new Timer().schedule(task, after);
task: Method that you to be executed.
after: time interval for initial execution of timer.(in milliseconds)
interval: intermediate time to repeat alarm
for your reference:
class UpdateTimeTask extends TimerTask {
public void run() {
firstLinearLayout.setVisibility(View.VISIBLE);
secondRelativeLayout.setVisibility(View.VISIBLE);
}
}
To start timer:
timer = new Timer();
timer.schedule(new UpdateTimeTask(), 3000);

System.Timers.Timer Elapsed event fired more than once time in Windows Service

I'm working on a Windows Service with a timer to schedule a job each interval of time.
It seems that the timer elapsed event is fired more than one time.
Here a code sample:
private static System.Timers.Timer _timer = new System.Timers.Timer();
protected override void OnStart(string[] args)
{
_timer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent);
_timer.Interval = 1000;
_timer.Enabled = true;
_timer.Start();
}
private void OnTimedEvent(object source, System.Timers.ElapsedEventArgs e)
{
_timer.Enabled = false;
_timer.Stop();
//Do the job
_timer.Enabled = true;
_timer.Start();
}
Can you help me?
Thank you
The signal to raise the Elapsed event is always queued for execution
on a ThreadPool thread, so the event-handling method might run on one
thread at the same time that a call to the Stop method runs on another
thread. This might result in the Elapsed event being raised after the
Stop method is called. The code example in the next section shows one
way to work around this race condition.
Quoted from: Timer.Stop Method. Please see the code sample on the page.

How to listen for resize events in JavaFX

How can I detect when a Scene or Stage changes size in JavaFX 2.1? I cannot find any EventHandler for this.
There are heightProperty and widthProperty. You can use these properties for binding, or add listeners to them.
public void start(Stage stage) {
Scene scene = new Scene(new Group(), 300, 200);
stage.setScene(scene);
stage.titleProperty().bind(
scene.widthProperty().asString().
concat(" : ").
concat(scene.heightProperty().asString()));
stage.show();
}
Or see next example: https://stackoverflow.com/a/9893911/1054140
A way to perform an action after re-sizing a scene was finished you can do this:
(Note: there maybe better ways to do this, for me it did the job)
final Stage primaryStage = getStage() // get your stage from somewhere
// create a listener
final ChangeListener<Number> listener = new ChangeListener<Number>()
{
final Timer timer = new Timer(); // uses a timer to call your resize method
TimerTask task = null; // task to execute after defined delay
final long delayTime = 200; // delay that has to pass in order to consider an operation done
#Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, final Number newValue)
{
if (task != null)
{ // there was already a task scheduled from the previous operation ...
task.cancel(); // cancel it, we have a new size to consider
}
task = new TimerTask() // create new task that calls your resize operation
{
#Override
public void run()
{
// here you can place your resize code
System.out.println("resize to " + primaryStage.getWidth() + " " + primaryStage.getHeight());
}
};
// schedule new task
timer.schedule(task, delayTime);
}
};
// finally we have to register the listener
primaryStage.widthProperty().addListener(listener);
primaryStage.heightProperty().addListener(listener);
this is too old and basic but it might help a noob like me
you can add a listener to width and height properties
stage.heightProperty().addListener(e ->{
handle....
});
stage.widthProperty().addListener(e ->{
handle....
});

Seeking C# threading clarification

I'm new to threading; in fact I'm not even trying to multi- thread the Windows Forms app I'm working on, but all of my searches on this issue lead me to the topic of multithreading. When debugging in Visual Studio 2010 Express, it seems to "jump around" to use the term I've seen others use to describe the same problem. When I let it run, sometimes it runs as expected, other times it just seems to keep running, getting hung up.
In trying to hone my question, I think I need to figure out:
If the timer class calls a method on a different thread, and there isn't an obvious danger of unpredictable instance values/ state corruption in the executing code (there aren't any conditional checks of instance variables etc), why would that method called by the timer appear to behave unpredictably? To me it seems that the code should run synchronously, and if a different thread is used for part of the process, so be it. I can't see where there is opportunity for thread corruption.
When the program starts, it prompts for the timer to be set to run a data download process. After the procedure runs, the timer is set again to a default time, at the end of the procedure. Consistently, the initial timer setting works, and fires as expected, running the data download process... it's that data download method, somewhere within it it goes awry. The last line of code is what sets the timer again, but I can't tell if it's getting hit while debugging it. (jumping around)..
I've added relevant code below... and I stepped into every procedure in my code from the beginning... they all show current thread id 10. This is up to an including the timer firing off, and stopping at a breakpoint at the very next line to execute, which is the data download process. The current thread at that point: 14. I've built the solution before running it/ trying to debug btw. Any ideas?
public partial class frmTradingAppMain : Form
{
private TradingAppDataRunManager drm;
private void frmTradingAppMain_Shown(object sender, EventArgs e)
{
drm = new TradingAppDataRunManager();
drm.StatusChanged += new DataRunManager.DRMStatusChangeHandler(UpdateFormData);
drm.InitializeOrScheduleDataRun();
}
private void UpdateFormData()
{
this.Invoke(new DataRunManager.DRMStatusChangeHandler(UpdateFormDataImpl));
}
private void UpdateFormDataImpl()
{
lblDataDwnLoadManagerStatus.Text = Convert.ToString(drm.Status);
if (drm.Status == DataRunManager.DRMStatus.Inactive)
{
lblNextScheduledDataDownloadDate.Text = "Date not set.";
lblNextScheduledDataDownloadTime.Text = "Time not set.";
}
else
{
lblNextScheduledDataDownloadDate.Text = drm.DateTimeOfNextScheduledDataRun.ToShortDateString();
lblNextScheduledDataDownloadTime.Text = drm.DateTimeOfNextScheduledDataRun.ToShortTimeString();
}
}
}
public abstract class DataRunManager
{
protected DataRunTimer dataRuntimer;
public delegate void DRMStatusChangeHandler();
public event DRMStatusChangeHandler StatusChanged;
public DRMStatusChangeHandler statusChanged;
public void InitializeOrScheduleDataRun()
{
if (DataRunIsAvailable() && UserWouldLikeToPerformDataRun())
RunMainDataProcedure(null);
else
ScheduleDataRun();
}
public void RunMainDataProcedure(object state)
{
start = DateTime.Now;
Status = DRMStatus.Running;
StatusChanged();
GetDataCollections();
foreach (DataCollection dcl in dataCollectionList)
{
dcl.RunDataCollection();
dcl.WriteCollectionToDatabase();
}
PerformDBServerSideProcs();
stop = DateTime.Now;
WriteDataRunStartStopTimesToDB(start, stop);
SetDataRunTimer(DateTimeOfNextAvailableDR());
}
public void ScheduleDataRun()
{
FrmSetTimer frmSetTimer = new FrmSetTimer(DateTimeOfNextAvailableDataRun);
DateTime currentScheduledTimeOfNextDataRun = DateTimeOfNextScheduledDataRun;
DRMStatus currentStatus= Status;
try
{
frmSetTimer.ShowDialog();
DateTimeOfNextScheduledDataRun = (DateTime)frmSetTimer.Tag;
SetDataRunTimer(DateTimeOfNextScheduledDataRun);
}
catch
{
Status = currentStatus;
DateTimeOfNextScheduledDataRun = currentScheduledTimeOfNextDataRun;
}
}
}
public class DataRunTimer
{
System.Threading.Timer timer;
public DataRunTimer(){}
public void SetNextDataRunTime(TimerCallback timerCallback, DateTime timeToSet)
{
if (timer == null)
timer = new System.Threading.Timer(timerCallback);
TimeSpan delayTime = new TimeSpan(timeToSet.Day - DateTime.Now.Day, timeToSet.Hour - DateTime.Now.Hour, timeToSet.Minute - DateTime.Now.Minute,
timeToSet.Second - DateTime.Now.Second);
TimeSpan intervalTime = new TimeSpan(0, 0, 10);
timer.Change(delayTime, intervalTime);
}
public void DataRunTimerCancel()
{
if (timer != null)
timer.Dispose();
}
}

Resources