Xamarin Forms: creare un timer

Se all’interno della tua App Xamarin Forms desideri scrivere un timer senza scendere sul device specifico puoi farlo ad alto livello in maniera molto semplice. Bastera’ utilizzare Device.StartTimer e nel seguente paragrafo vedremo due esempi “identici”, ma con una sola differenza. Quale? Andiamo a scoprirla!

xamarin forms (basic) timer

Guardando la documentazione di Device.StartTimer dobbiamo specificare un TimeSpan interval ed una Func callback

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
//
// Summary:
//     Starts a recurring timer using the device clock capabilities.
//
// Parameters:
//   interval:
//     The interval between invocations of the callback.
//
//   callback:
//     The action to run when the timer elapses.
//
// Remarks:
//     While the callback returns true, the timer will keep recurring.
//     If you want the code inside the timer to interact on the UI thread (e.g. setting
//     text of a Label or showing an alert), it should be done within a BeginInvokeOnMainThread
//     expression, which will be nested inside the timer (see below).
public static void StartTimer(TimeSpan interval, Func<bool> callback);

Ora -dopo avere visto la teoria- vediamo un esempio pratico e molto minimale.

  • AppConfiguration.TimerMilliseconds: configurazione che indica ogni quanto millisecondi effettuare il contenuto del timer

Nel seguente esempio il codice “Your Code” verra’ eseguito una ed una sola volta dopo il TimeSpan indicato.

1
2
3
4
5
Device.StartTimer(TimeSpan.FromMilliseconds(AppConfiguration.TimerMilliseconds), () =>
{
    // Your Code
    return false;
});

Se -in caso contrario- desiderate esegure il codice ogni “TimeSpan” vi bastera’ cambiare il ritorno in return true consentendo al timer di riattivarsi in maniera autonoma.

1
2
3
4
5
Device.StartTimer(TimeSpan.FromMilliseconds(AppConfiguration.TimerMilliseconds), () =>
{
    // Your Code
    return true;
});

Nel momento in cui la vostra applicazione venga messa in background dall’utente, il timer restera’ attivo sino alla chiusura totale dell’app (se non e’ previsto via codice una via di uscita)