Home > Blockchain >  How to change a label value at run time, every 8 hours daily using timer
How to change a label value at run time, every 8 hours daily using timer

Time:06-09

Hello I am having a very hard time trying to change the value of a label in a Winforms application using a System.Windows.Forms.Timer I need the label to show a number 1 from 6am till 2pm. a number 2 from 2pm till 10pm and a number 3 from 10pm till 6am everyday. This is what I've tried so far.

I added a clock to my form, I changed the interval on the clock to 28800000

InitializeComponent();
//8 Hour timer
Timer timer5 = new Timer();
timer5.Interval = 28800000; // 8 hours
timer5.Tick  = new EventHandler(timer5_Tick);
timer5.Start(); 

On the Timer tick I've added this.

private void timer5_Tick(object sender, EventArgs e)
{
    _ = DateTime.Now.Hour;

    if (DateTime.Now.Hour >= 6 && DateTime.Now.Hour < 1400)
    {
        //First shift 06:00am through 2:00pm
        LblShift.Text = "2";
    }
           
    if (DateTime.Now.Hour >= 1400 && DateTime.Now.Hour < 2200)
    {
        //Second shift 02:00pm through 10:00pm
        LblShift.Text = "2";
    }

    if (DateTime.Now.Hour >= 2200 && DateTime.Now.Hour < 6)
    {
        //Second shift 02:00pm through 10:00pm
        LblShift.Text = "3";
    }
}

The label will change when I first open the form, but it will not update anymore after that. What am I doing wrong? I would appreciate any help

CodePudding user response:

Long interval timers tend to be less reliable. Instead, set your timer for a much shorter interval, like one minute, and then check the time on each tick (which you do anyway) to know what value to display:

InitializeComponent();
Timer timer5 = new Timer();
timer5.Interval = 60*1000; // 60 seconds
timer5.Tick  = new EventHandler(timer5_Tick);
timer5.Start();

I need the label to show a number 1 from 6am till 2pm, a number 2 from 2pm till 10pm, and a number 3 from 10pm till 6am

We can simplify the conditional checks for this if we go in order through the day (and include 3rd shift twice)

private void timer5_Tick(object sender, EventArgs e)
{
    var h = DateTime.Now.Hour;

    if (h < 6) 
    {
        LblShift.Text = "3";
    }
    else if (h < 14)
    {
        LblShift.Text = "1";
    }
    else if (h < 22)
    {
        LblShift.Text = "2";
    }
    else
    {
        LblShift.Text = "3";
    }
}

Or for fun:

private List<(int, int)> shiftHourMap = new List<(int, int)> {(6,3),(14,1),(22,2),(99,3)};
private int CurrentShift()
{
    return shiftHourMap.First(m => DateTime.Now.Hour < m.Item1).Item2;
}

private void timer5_Tick(object sender, EventArgs e)
{    
    lblShift.Text = CurrentShift().ToString();
}
  • Related