Skip to content

How to create a timer ?

Gammasoft edited this page Nov 14, 2023 · 6 revisions

| xtd | News | Gallery | Examples | Downloads | Documentation | Wiki | Support | Sources | Project | Gammasoft |

There are many method to create a timer with xtd.

Using xtd::threading::timer class instantiation

#include <xtd/diagnostics/stopwatch>
#include <xtd/threading/timer>
#include <xtd/console>

using namespace xtd;
using namespace xtd::diagnostics;
using namespace xtd::threading;

auto main()->int {
  auto stopwatch1 = stopwatch::start_new();
  console::write_line("start at {}", stopwatch1.elapsed());

  auto timer1 = timer([&] {
    console::write_line("do something at {}", stopwatch1.elapsed());
  }, 200_ms, 100_ms);
  
  thread::sleep(1000_ms);
  timer1.close();
  
  console::write_line("stop at {}", stopwatch1.elapsed());
}

Using xtd::timers::timer class instantiation

#include <xtd/diagnostics/stopwatch>
#include <xtd/timers/timer>
#include <xtd/console>

using namespace xtd;
using namespace xtd::diagnostics;
using namespace xtd::threading;
using namespace xtd::timers;

auto main()->int {
  auto stopwatch1 = stopwatch::start_new();
  console::write_line("start at {}", stopwatch1.elapsed());

  auto timer1 = timer(100_ms);
  timer1.elapsed += [&] {
    console::write_line("do something at {}", stopwatch1.elapsed());
  };
  timer1.enabled(true);
  
  thread::sleep(1000_ms);
  timer1.enabled(false);

  console::write_line("stop at {}", stopwatch1.elapsed());
}

Using xtd::forms::timer class instantiation

#include <xtd/diagnostics/stopwatch>
#include <xtd/forms/application>
#include <xtd/forms/debug_form>

using namespace xtd;
using namespace xtd::diagnostics;
using namespace xtd::forms;

auto main()->int {
  auto stop_watch1 = stopwatch::start_new();
  auto debug_form1 = debug_form {};
  auto form1 = form {};

  auto timer1 = timer {};
  timer1.interval(100_ms);
  timer1.tick += [&] {
    debug::write_line("do something at {}", stop_watch1.elapsed());
    if (stop_watch1.elapsed().total_milliseconds() > 1000.0) timer1.enabled(false);
  };
  timer1.enabled(true);

  application::run(form1);
}

Remarks

You can of course use your own timer or any other third-party thread library.

See

Clone this wiki locally