Alexia
Alexia

Reputation: 83

How do i make TimeSpan start ticking in seconds?

How do i make my TimeSpan object tick in seconds?

private TimeSpan time;

public Clock{
    time = new Timespan(0, 0, 0);
}

public void Tick()
{
   //start ticking in seconds
}

Upvotes: 1

Views: 918

Answers (1)

Jake Reece
Jake Reece

Reputation: 1168

A TimeSpan is a data type used for storing time. However, you need a Timer if you want something to run/update at an interval. You can implement a Timer like so:

using System;
using System.Timers;

public class Clock
{
    private static Timer aTimer;
    private TimeSpan time;

    public Clock()
    {
        // Initialize the time to zero.
        time = TimeSpan.Zero;

        // Create a timer and set a one-second interval.
        aTimer = new System.Timers.Timer();
        aTimer.Interval = 1000;

        // Hook up the Elapsed event for the timer. 
        aTimer.Elapsed += OnTimedEvent;

        // Start the timer.
        aTimer.Enabled = true;
    }

    private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
    {
        time = time.Add(TimeSpan.FromSeconds(1));
    }
}

Then, whenever you create a new Clock() object, it will get its own time and update every second.

See this article from MSDN for more information about the Timer class.

Upvotes: 2

Related Questions