how to create a countdown timer in visual studio using datetimepicker - c#

this may sound stupid for some of you but please bear with me. I am trying to create a windows form application that has 2 datetimepicker controls. They are intended to set a time range (date selection has been disabled). After the user sets the range and hits the confirm button, the program needs to display 'A' till the limit and reached and when the timer expires, display 'B'.
This is my code right now in the click event of the confirm button
int a=0;
TimeSpan time = DateTime.Now.TimeOfDay;
TimeSpan timer = dateTimePicker2.Value - dateTimePicker1.Value;
MessageBox.Show("Timer set. Device will shutdown in " + timer);
timer = timer + time;
while (time!=timer)
{
time = DateTime.Now.TimeOfDay; ;
if(a==0)
{
MessageBox.Show("B");
a = 1;
};
};
if (a == 1)
{
MessageBox.Show("A");
a = 0;
}
My logic behind this piece of code was this: First find the difference between the two time ranges. Then add this difference to the current system time and do a while loop to check if that time has reached.If not display B. When the current system time reaches the time, display A. I have spend hours over this and cant get it working. When running this code it just displays B and never A.
I'm new to visual studio and this is my first project.

The problem is likely to be this test:
while (time!=timer)
it's highly likely that the current time will never be exactly equal to the second time you've picked. You should change this to:
while (time < endTime)
With this you'll be able to get rid of your variable a and just display "A" once the loop finishes.
Having said all this, MessageBox.Show will block the loop until you dismiss it so you really need to find some other way of indicating that you're still in the loop.

Related

C# Console - how to set up a countdown timer limtit to user input with readline

I am trying to write a very simple mathematical game in C# Console Application. The program will ask a simple mathematical question to the user. The user must respond by typing the answer and then press enter. I used the code
userinput = Convert.ToInt32(Console.Readline());
code to do this. However, I need the user to assign the value of userinput variable in three seconds after the problem is asked. So, I have to start a countdown timer immediately after the problem is asked. If the user does not type the answer and hit enter within three seconds, the program will display the message "timeout for this question" and immediately display the next question. If the user can type the answer and hit enter within three seconds, the program should immediately stop the countdown timer and evaluate the user's answer. I would be very happy if you can help me with that. Thank you very much in advance.
Note: I read the similar threads but they are based on readykey type user inputs. I need a readline type input.
Some pseudocode:
ask the problem;
start the timer;
if (the user types the answer and presses enter within three seconds)
{
evaluate the answer;
go to the next question;
}
else
{
prompt timeout;
go to the next question;
}
Countdown timers are a great way to add an extra touch of challenge and excitement to any game or activity. In this article, we will provide you with a step-by-step guide on how to set up a countdown timer limit to user input with readline in C# Console.
The first step is to import the C# Console namespace. This will give you access to the readline and Console classes, which are required for setting up a countdown timer. To do this, simply place the following code in your project:
using System;
Next, you need to create a method that will be used to set the timer limit. In this example, we are going to use a loop to count down from the user-specified value to zero. To do this, declare a new integer variable called ‘limit’ and set it to the result of the ReadLine() method. This method will prompt the user to enter a value they want to use as a timer limit:
int limit = int.Parse(Console.ReadLine());
Now, you will need to set up the loop for the countdown. This loop will continue running until it reaches zero. Inside the loop, you can use the Console.WriteLine() method to print out current time left for the user. After each iteration, you need to decrease the value of the limit variable by one:
while (limit > 0)
{
Console.WriteLine("Time left: " + limit);
limit--;
}
Finally, you will need to add some code to print out a message when the timer has reached zero. This can be done by using the Console.WriteLine() method again, this time with a message that informs the user that their time has run out:
if (limit == 0)
{
Console.WriteLine("Time's up!");
}
With that, you have successfully created a countdown timer limit to user input with readline in C# Console! This simple script can be used to add a bit of extra challenge and excitement to any game or activity you create.

Are DateTimes passed by reference in C#? If not, why is my object updating as I change a variable?

I have ran into a problem which I simply cannot get my head around. When I debug the program, I can see the program works fine - this is the strange part.
The issue I am facing is when I append to a List with the new object - it seems to completely change. Let me explain better by showing my code.
System.DateTime timeNow = System.DateTime.Now;
List<Train> trainsOnNet = new List<Train>();
for(int i = 1; i <= 3; i++)
{
Train t = new Train();
t.NewCarrige(true, "A"[0]);
t.NewCarrige(false, "B"[0]);
t.addStation(App.Stations.FirstOrDefault(x => x.GetShortCode().Equals("MTG")));
t.addStation(App.Stations.FirstOrDefault(x => x.GetShortCode().Equals("BNS")));
t.addStation(App.Stations.FirstOrDefault(x => x.GetShortCode().Equals("BSH")));
int minsToAdd = 5;
t.GetStations().ForEach(x =>
{
timeNow = timeNow.AddMinutes(minsToAdd);
x.SetArrivalTime(timeNow);
minsToAdd += 10;
});
timeNow = timeNow.AddMinutes(15);
trainsOnNet.Add(t);
}
When I add t to the trainsOnNet List, the time seems to change to the last time that the loop will generate, even before it generates.
If I place a stopper on this line, I can see that the t instance has the correct time variables (ie, 5 minutes from the current execution time and then 10 minutes between each). However, when I then press continue and inspect the trainsOnNet list. This time has been changed to the next trains set of times.
It appears to me that timeNow is being passed by reference, and as the loop increases the time, the stored time updates until I am left with 3 trains all saying the same time.
For example, if I execute the program at 1951 with a stopper on trainsOnNet.Add(t) I can see that t holds 3 stations, in which the first stations Arrival time is 19:56 and the second is 20:11 and 20:26. Perfect. I then hit continue and inspect the newly appended object to my list. On inspection, the t instance arrival time properties have now changed to:
20:56, 21:11, 21:36
Doing the maths of my code, the next train should arrive 20 minutes after the previous train has arrived at the end station. Which brings me to 20:46. Thus deeming it more confusing why the first train is being changed past the second trains expected time let alone being updated without stating to do so.
Any ideas would be greatly appricated.
Stop on the line on the first execution:
Stop on same line, after pressing continue (changed properties):
As you can see, the values are being changed? In this case, by a whole hour?
System.DateTime is a "value type". You can check that by seeing on your intellisense in Visual Studio or in the documentation that it is declared as a struct, not a class (the latter are reference types).
Your problem, however, is not really about this.
It's not clear what you exactly intend to do, and the flaw is probbaly in your logic implementation.
1 - you reuse the same variable timeNow for all iterations, it's hard (at least to me) to keep track on how much it is supposed to be and how much the value is after a few "mental" iterations.
2 - you set minsToAdd to 5, then increase it by 10 in loop. So, after a few iterations of the inner loop, minsToAdd gets these values :
15, 25, 35, 45, etc...
Then, you add this to timeNow, so imagine that timeNow is 00:00 at the beginning, in the inner loop it gets values
00:05,
00:05 + 15min = 00:20
00:20 + 25min = 00:55
00:55 + 35min = 01:30
etc...
and after the inner loop you add 15 min to the last value.
Is that what you expect?
Try to change these two lines:
timeNow = timeNow.AddMinutes(minsToAdd);
x.SetArrivalTime(timeNow);
To just:
x.SetArrivalTime(timeNow.AddMinutes(minsToAdd));
As others explained, you're overriding the timeNow variable with each iteration. This change should give you the expected result.

How to make a stopwatch windows form application

I am currently trying to make a chronometer in c# using the timespan class. So far I have been able to appropriately start, pause, and stop the chronometer, but I have been asked to make a lap button that registers the time in the chronometer upon click, and make another button that opens another form to list said lap times. It is this part that i have trouble with.
Basically I need help with registering the time and retaining those values to later show them in a list. I appreciate your time and willingness to help.
This is some of the code i tried to make for registering the time along with making a different class called LapList, it didnt go very well.
private void button2_Click(object sender, EventArgs e)
{
TimeSpan Et = Crono.Elapsed;
TimeSpan LapTime = Et - LastBreakTime;
LastBreakTime = Et;
++Lapcount;
LapList.getTimeSpan().Add(LapTime);
}
Thanks again for your time.
It seems you should be able to store the DateTime.Now of each click of the Lap button, then use DateTime2 - DateTime1 to give you a TimeSpan object that can be displayed?
So each click of Lap button effectively performs a List.Add(DateTime.Now) and your lap display iterates over the list, performing List[I] - List[I-1]
.NET already has a Stopwatch for measuring time and returning the elapsed time as a TimeSpan, Milliseconds or Ticks.
You can start a new Stopwatch with Stopwatch.StartNew and store the instance in a field until you need to check the elapsed time. You can also pass the instance from method to method, or store it in an array or dictionary so you can time multiple executions

How to get a console app to run a function once a month (and not more), indefinitely?

Writing a C# app to run some scheduled tasks, all I really need is something to continuously monitor the date and time, and call a function once, on the 28th of each month, and then go back to waiting patiently for the 28th of the next month to come around.
I guess it will be using System.Threading.Thread.Sleep() in some way, but as for the specific conditions under which it should run, and how to prevent it from running multiple times on the date in question, I'm not sure...
Any help greatly appreciated :)
You can set up a Windows Scheduled Task to run your console app on the 28th of every month.
It's simple, easy and light on the server's resources since your app wouldn't take up any resources between runs.
If the PC is down, you can also tick the option: "Run task as soon as possible after a scheduled start is missed."
There are a huge number of options for you to customize how your task is run, such as:
Only run when a user is logged on.
Specify program parameters.
Start the task only if the computer is on AC power.
Start the task only if the following network connection is available.
Not all option may be available in all versions of Windows.
You can use loop which runs each second and checks for the date, and at specified date acts and waits for the next month. You will use System.Threading.Thread.Sleep() to put it on wait for 1 second.
You can wait for the next date by having last date traacked and calculating next date by adding to it 1 monnth.
DateTime? counter = null;
while (1 = 1)
{
if (DateTime.Now.Day == 28 && (!counter.HasValue || counter.Value.Date < DateTime.Now.Date ))
{
counter = DateTime.Now;
DoSomething();
}
Thread.Sleep(1000);
};

How to start some Method every 20 days (Windows Phone)

In my Windows Phone Applicarion I need to implement logic to start some Method every 20 days, how can I implement this?
public void Method()
{
//some logic
}
Update
For example I can fix the first start of some method, then every start of application I will fix the current date time and them calculate the differens, and if the difference between the last and first sstart of some method will be more than 30 days I will start Method(). So how can I calculate the difference (days)?
Not easily!
The best fit for this is to use a Scheduled Agent - but this runs ever 30 minutes approximately - so you would need to keep track of the last run time and act accordingly.
The other issue with this is that if the app that is associated with the scheduled task is not run at least ever 14 days the task is disabled.
HTH,
Rupert.
So you want to know if it's 20 (or more?) days since you last performed an action in your app.
Let's assume that you save the date to calculate from as a DateTime called savedDate. (I'm assuming you can put this in and retrieve from IsolatedStorage without issue.)
Then you can just do a simple test against the current date:
if (saveddate.Date.AddDays(20) <= DateTime.UtcNow.Date)
{
// Do your every 20 days action here
// and then probably reset savedDate to the current date?
}
What about a push notification. You let the server take care of this. When the time is ready it sends a notification to the phone which does things accordingly.
Edit:
To find the difference you can do something like this
TimeSpan span = endTime.Subtract(startTime);
if(span.Days >= 20)
Method();
You could store the last time the method was ran in Isolated Storage, and then use the Scheduled Agent to run every 30min:
if (DateTime.Now.Subtract(LastTimeRanFromIsolatedStorage) > TimeSpan.FromDays(20))
{
Method();
}

Categories

Resources