c# certain timer sequence

timer autoreset in c#
c# timer stop
c# second timer
timer.start c#
timer clock in c#
timer task in c#
show timer in c#
c# timer loop

I want to do a sequence of timed events for a morse code blinking light. The programm should be able to be worked with while the light is blinking.

So there will be a Long pause at the beginning and then it will start to blink long and short signs with small pauses in between and then start over again.

Example Sequence

  • Light off 3000ms
  • Light on 1200ms
  • Light off 500ms
  • Light on 400ms
  • Light off 500ms
  • Light on 1200ms
  • Light off 500ms
  • Light on 400ms
  • start over again

I tried this code but it only freezes the programm

private void Morse()
{
    System.Timers.Timer MorseCode = new System.Timers.Timer(3000);
    MorseCode.Elapsed += new ElapsedEventHandler(long);
    MorseCode.Elapsed += new ElapsedEventHandler(short);
    MorseCode.Elapsed += new ElapsedEventHandler(long);
    MorseCode.Elapsed += new ElapsedEventHandler(short);

    void short(object sender, ElapsedEventArgs e)
    {
        MorseCode.Elapsed += new ElapsedEventHandler(ColorChange);
        MorseCode.Interval = 400;
        MorseCode.Elapsed += new ElapsedEventHandler(ColorChange);
        MorseCode.Interval = 500;
    }
    void long(object sender, ElapsedEventArgs e)
    {
        MorseCode.Elapsed += new ElapsedEventHandler(ColorChange);
        MorseCode.Interval = 1200;
        MorseCode.Elapsed += new ElapsedEventHandler(ColorChange);
        MorseCode.Interval = 500;
    }
    void ColorChange(object sender, ElapsedEventArgs e)
    {
        if(BlinkLight.BackColor == Color.Gray)
        {
            BlinkLight.BackColor = Color.DodgerBlue;
        }
        else
        {
            BlinkLight.BackColor = Color.Gray;
        }
    }    
}

So how do i make a sequence with different timings for a blinking light?

You could use the Task Parallel Library for this, this is included in .NET 4 and up. This will produce neat readable code like this:

private void Morse()
{
    BlinkShort().ContinueWith(          //
        BlinkShort).ContinueWith(       //  S
        BlinkShort).ContinueWith(       //
        BlinkLong).ContinueWith(        //
        BlinkLong).ContinueWith(        //  O
        BlinkLong).ContinueWith(        // 
        BlinkShort).ContinueWith(       //
        BlinkShort).ContinueWith(       //  S
        BlinkShort);                    // 
}

Example implementation of helper methods:

private Task BlinkShort(Task previousTask = null)
{
    var action = new Action(() =>
    {
        SetColorSafe(true);
        Task.Delay(400).Wait();
        SetColorSafe(false);
        Task.Delay(500).Wait();
    });
    var t = Task.Run(action);
    if (previousTask != null) // already threaded
    {
        t.Wait();
    }

    return t;
}
private Task BlinkLong(Task previousTask = null)
{
    var action = new Action(() =>
    {
        SetColorSafe(true);
        Task.Delay(1200).Wait();
        SetColorSafe(false);
        Task.Delay(500).Wait();
    });
    var t = Task.Run(action);
    if (previousTask != null) // already threaded
    {
        t.Wait();
    }

    return t;
}

private void SetColorSafe(bool on)
{
    if (InvokeRequired)
    {
        Invoke(new Action(() => {
            SetColorSafe(on);
        }));
        return;
    }
    if (on)
    {
        BackColor = Color.DodgerBlue;
    }
    else
    {
        BackColor = Color.Gray;
    }
}

Timer.Interval Property (System.Timers), The interval is greater than MaxValue, and the timer is currently enabled. (2000 milliseconds), sets up an event handler for the event, and starts the timer. C# Copy. using System; using System.Timers; public class Example { private static  For this purpose I create a timer with period twice the maximum answer time. In my case it is 2 * 125 ms = 250 ms. If the answer comes in predefined time interval, I destroy already running timer. If the answer doesnt come in predefined interval, timer initiates some action. After this action we can destroy it.

Use Microsoft's Reactive Framework for this - NuGet "System.Reactive.Windows.Forms".

Then you can do this:

int[] timings = new [] { 3000, 1200, 500, 400, 500, 1200, 500, 400 };

IObservable<System.Drawing.Color> sequence =
    Observable
        .Generate(
            0,
            x => x < timings.Length,
            x => x + 1,
            x => x % 2 == 1 ? System.Drawing.Color.DodgerBlue : System.Drawing.Color.Gray,
            x => TimeSpan.FromMilliseconds(timings[x]));

IDisposable subscription =
    sequence
        .Repeat()
        .ObserveOn(BlinkLight)
        .Subscribe(color => BlinkLight.BackColor = color);

Multithreading in C# 5.0 Cookbook, The outerscope represents a subscription to thetimer, the inner subscriptions dealwiththe combined sequence query and theside effectsquery, respectively. I want to do a sequence of timed events for a morse code blinking light. The programm should be able to be worked with while the light is blinking. So there will be a Long pause at the beginning and then it will start to blink long and short signs with small pauses in between and then start over again. Example Sequence. Light off 3000ms; Light on 1200ms

I like Enigmativity's solution. If you know System.Reactive, that's a goog choice.

This a simple solution using a asyncronous Task. I'm passing to the async method: - a List<Tuple<int, int>> that represents the spaces and durations of the signals - a Control refrence that will serve as the visual output - a CancellationToken, used to signal when the Task should be terminated.

The Task can be cancelled, then start over again with the same sequence or a new one. If not cancelled, the Task will go on indefinitely, playing the current sequence. Here, I'm using a Button to start the Task. I could be anything else.

Note that I've modified the sequence and the timings a little. The pause between each sequence iteration is at the end of the sequence, so it starts the signal immediately, then it pauses it after each sequence is executed.

When a cancellation request is issued, the Task will complete the sequence before cancelling: if (token.IsCancellationRequested) return; is checked only after a sequence is completed, to avoid messing with the timings. But this could be modified to check for cancellation after each long pause.

CancellationTokenSource source;
CancellationToken token;

private void button1_Click(object sender, EventArgs e)
{
    if (source != null)
    {
        source.Cancel();
        source.Dispose();
        source = null;
        return;
    }

    source = new CancellationTokenSource();
    token = source.Token;
    List<Tuple<int, int>> MorseCodeSequence = new List<Tuple<int, int>>()
    {
        new Tuple<int, int>(1200, 200),
        new Tuple<int, int>(400, 200),
        new Tuple<int, int>(1200, 200),
        new Tuple<int, int>(400, 2000)
    };

    Task.Run(()=> MorseSequence(MorseCodeSequence, this.btnMorse, token));
}

public async Task MorseSequence(List<Tuple<int, int>> MorseSequence, Control MorseCodeOutputObject, CancellationToken token)
{
    while (true)
    {
        foreach (Tuple<int, int> MorseTiming in MorseSequence)
        {
            MorseCodeOutputObject.BeginInvoke(new MethodInvoker(() =>
                { MorseCodeOutputObject.BackColor = Color.Cyan; }));
            await Task.Delay(MorseTiming.Item1);
            MorseCodeOutputObject.BeginInvoke(new MethodInvoker(() =>
                { MorseCodeOutputObject.BackColor = Color.Gray; }));
            await Task.Delay(MorseTiming.Item2);
        }
        if (token.IsCancellationRequested) return;
    };
}

The SOS sequence

List<Tuple<int, int>> SOSMorseSequence = new List<Tuple<int, int>>()
{
    new Tuple<int, int>(400, 200),
    new Tuple<int, int>(400, 200),
    new Tuple<int, int>(400, 300),
    new Tuple<int, int>(1200, 200),
    new Tuple<int, int>(1200, 200),
    new Tuple<int, int>(1200, 300),
    new Tuple<int, int>(400, 200),
    new Tuple<int, int>(400, 200),
    new Tuple<int, int>(400, 2000),
};

C# Timers In A Sequence, Hello, i am currently coding a lift server which involves the use of timers which will be activated upon clicking a certain button, i have gotten  Time traveling starts from the present time, which is specified as an argument of the Walk() method of the time sequence. Note that the iteration process will never stop unless we terminate it intentionally, or we are out of the range of the DateTime values. Some times, you may want to iterate through two separate sequences simultaneously.

Multithreading with C# Cookbook, works The ability to use LINQ against the Observable event sequences is the main advantage of the The timer event's sequence is printed in the first column. The second approach, where we build an enumerable sequence of observables and then .Concat() works (and I can't see any potential problems with it in terms of multiple subscriptions or cancellation), but has more overhead than necessary in that it produces a separate Observable for every single point in time, with each of these producing a single value. This wouldn't be necessary if we had a single observable to produce the values in order, and that's essentially what the third piece of code

C# Timer and StopWatch Classes, Properties (some of them). AutoReset. This is boolean and indicates whether the Timer should be raised only one event (false) or a sequence of them (true). C# DateTime Examples. Compute date and time values. Get relative dates and call DateTime constructors and properties. DateTime. Each day the sun rises—bright light marks a new day. From Earth's surface we view the sun's path. What begins as motion gains meaning as time. Type info.

Trying to create a sequential tasks within a UI with an interval timer, While the delay is happening there are several buttons that need to be serviced in case of Skip,Pause,Cancel so that the user is not locked in  The Timer component is a server-based timer that raises an Elapsed event in your application after the number of milliseconds in the Interval property has elapsed. You can configure the Timer object to raise the event just once or repeatedly using the AutoReset property.

Comments
  • In WinForms apps use System.Windows.Forms.Timer, because it guarantees to run event handler code on UI thread - you can create it through designer. Also, I would recommend using one timer to handle all this logic with small interval like 100, instead of having 8 timers.
  • Thank you for your reccomendation i will try it that way.
  • Thank you that works great for me.