重要的應用程式介面
瞭解如何建立定期重複的工作專案。
建立定期工作專案
使用 CreatePeriodicTimer 方法來建立定期工作專案。 提供可完成工作的 Lambda 函數,並使用 時間 參數來指定提交時間之間的間隔。 期間是使用 TimeSpan 結構來指定。 每當設定的時段結束後,工作項目都會重新提交,因此請確保設定的時段足夠長,才能完成該工作。
CreateTimer 會傳回 ThreadPoolTimer 物件。 若要取消定時器,請儲存此物件。
注意 請避免為間隔指定零值(或任何小於一毫秒的值)。 這會導致定期定時器改為以單次定時器的形式運作。
附註 您可以使用 CoreDispatcher.RunAsync 來存取 UI,並顯示工作項目的進度。
下列範例會建立每 60 秒執行一次的工作專案:
TimeSpan period = TimeSpan.FromSeconds(60);
ThreadPoolTimer PeriodicTimer = ThreadPoolTimer.CreatePeriodicTimer((source) =>
{
//
// TODO: Work
//
//
// Update the UI thread by using the UI core dispatcher.
//
Dispatcher.RunAsync(CoreDispatcherPriority.High,
() =>
{
//
// UI components can be accessed within this scope.
//
});
}, period);
TimeSpan period;
period.Duration = 60 * 10000000; // 10,000,000 ticks per second
ThreadPoolTimer ^ PeriodicTimer = ThreadPoolTimer::CreatePeriodicTimer(
ref new TimerElapsedHandler([this](ThreadPoolTimer^ source)
{
//
// TODO: Work
//
//
// Update the UI thread by using the UI core dispatcher.
//
Dispatcher->RunAsync(CoreDispatcherPriority::High,
ref new DispatchedHandler([this]()
{
//
// UI components can be accessed within this scope.
//
}));
}), period);
處理定期工作項目的取消(非必須)
如有需要,您可以使用 TimerDestroyedHandler來取消週期性計時器。 使用 CreatePeriodicTimer 多載來提供一個額外 Lambda,以處理定期工作項目的取消。
下列範例會建立每隔 60 秒重複一次的定期工作項目,同時也會提供取消處理程式:
using Windows.System.Threading;
TimeSpan period = TimeSpan.FromSeconds(60);
ThreadPoolTimer PeriodicTimer = ThreadPoolTimer.CreatePeriodicTimer((source) =>
{
//
// TODO: Work
//
//
// Update the UI thread by using the UI core dispatcher.
//
Dispatcher.RunAsync(CoreDispatcherPriority.High,
() =>
{
//
// UI components can be accessed within this scope.
//
});
},
period,
(source) =>
{
//
// TODO: Handle periodic timer cancellation.
//
//
// Update the UI thread by using the UI core dispatcher.
//
Dispatcher->RunAsync(CoreDispatcherPriority.High,
()=>
{
//
// UI components can be accessed within this scope.
//
// Periodic timer cancelled.
}));
});
using namespace Windows::System::Threading;
using namespace Windows::UI::Core;
TimeSpan period;
period.Duration = 60 * 10000000; // 10,000,000 ticks per second
ThreadPoolTimer ^ PeriodicTimer = ThreadPoolTimer::CreatePeriodicTimer(
ref new TimerElapsedHandler([this](ThreadPoolTimer^ source)
{
//
// TODO: Work
//
//
// Update the UI thread by using the UI core dispatcher.
//
Dispatcher->RunAsync(CoreDispatcherPriority::High,
ref new DispatchedHandler([this]()
{
//
// UI components can be accessed within this scope.
//
}));
}),
period,
ref new TimerDestroyedHandler([&](ThreadPoolTimer ^ source)
{
//
// TODO: Handle periodic timer cancellation.
//
Dispatcher->RunAsync(CoreDispatcherPriority::High,
ref new DispatchedHandler([&]()
{
//
// UI components can be accessed within this scope.
//
// Periodic timer cancelled.
}));
}));
取消定時器
必要時,呼叫 Cancel 方法以停止定期工作項目重複。 如果工作專案在定期定時器取消時正在執行,則允許它完成。 TimerDestroyedHandler(如果提供的話)會在定期工作項目的所有實例完成時被調用。
PeriodicTimer.Cancel();
PeriodicTimer->Cancel();
備註
如需了解一次性計時器的資訊,請參閱 使用計時器提交工作項目。