Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am making a food ordering desktop application , so i want to calculate time between ordering food and delivering food so i added timers to the app and made a start and end buttons , on starting i start a time and put it interval value ,make a variable counter, count and save its value on end button to database , what i want to made is to start a new timer dynamically on new orders and when ending an order stop its timer
i tried inserting 3 timers and made variables c1,c2,c3 and made a loop to start timers on every order if interval!=null , but i didn't know how to stop a specific timer on ending the order
code :
int c1=0;
int c2=0;
int c3=0;
private void button_start_Click(object sender, EventArgs e)
{
if (timer1.Interval == null)
{
timer1.Start();
timer1.Interval = 1000;
}
else if (timer2.Interval == null)
{
timer2.Start();
timer2.Interval = 1000;
}
else if (timer3.Interval == null)
{
timer3.Start();
timer3.Interval = 1000;
}
}
Well as you have not shown us any code, let me assume that you at least have a class to encapsulate order.
public class Order
{
public int OrderNumber{get;set;}
///other properties
}
Now if you add following two properties and a method, your problem is resolved.
public class Order
{
public int OrderNumber{get;set;}
//other properties
public DateTime OrderPlacedOn{get;set;}
public DateTime OrderCompletedOn{get;set;}
public TimeSpan TimeToComplete()
{
if(OrderCompletedOn==DateTime.MinValue)//order not completed yet
return TimeSpan.FromSeconds(0);
return OrderCompletedOn - OrderPlacedOn;
}
}
This saves you from keeping countless timers. You can set values of start and complete on clicking of your buttons.
Related
I'm creating a calculator in Unity and faced with a problem.So I need to change bool value to write second number of my calculator.
My script attached to all the buttons(GameObjects) in the scene.
I need to change this value to true to write second number of calculator.
private bool input_second_num;
public void Input(){
if (calculate_label.text.Length < 15 && !input_second_num)
{
calculate_label.text += btnNumber;
first_num = long.Parse(calculate_label.text);
}
esle if (calculate_label.text.Length < 15 && input_second_num)
{
calculate_label.text += btnNumber;
second_num = long.Parse(calculate_label.text);
}
}
//Calls when clicking on action button
public void Action()
{
input_second_num = true;
calculate_label.text = " ";
}
At first input_second_num is false to write first number at first.When I'm changing input_second_num to true in another function clicking on action button and then trying to input second num, input_second_num is anyways false and I'm typing number for first_number.
Why is it so happening?
It's difficult to answer with the code posted and my initial observations require more than will fit into a comment.
You have posted two functions with the same signature public void Input(). I can't see how this code builds without issues; I must therefore assume that they are declared in different class types.
This function is incorrect:
public void Input()
{
else if (calculate_label.text.Length < 15 && input_second_num)
{
calculate_label.text += btnNumber;
second_num = long.Parse(calculate_label.text);
print("Second: " + second_num);
}
}
You're starting an if block statement with an else - is there code missing?
You state that you declared input_second_num as
private static input_second_num;
There is no data type assigned again I can't see how your code builds without issues.
Please revisit your question and show us more of your class code.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I've been working on a timer in c# just to mess around since I've never done it before. I wanted to have the OnTimedEvents method I was declaring in a separate class as I will be calling it in various other classes for various other tests, but I cannot invoke it properly without getting errors. Specifically, I am getting No Overload Method for Method '' Takes 0 Arguments. I cannot work around this as I have with other methods. This is the code:
class MSOfficeApps {
public static Timer aTimer;
public void appWord() {
var programCS = new Program();
Microsoft.Office.Interop.Word.Application WordObj;
WordObj = (Microsoft.Office.Interop.Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
for(int i = 0; i < WordObj.Windows.Count; i++) {
object idx = i + 1;
Microsoft.Office.Interop.Word.Window WinObj = WordObj.Windows.get_Item(ref idx);
Console.WriteLine(WinObj.Document.FullName);
aTimer = new System.Timers.Timer(600000); //Sets timer to 6 minute increments
aTimer.Elapsed += ElapsedEventHandler(programCS.OnTimedEvent()); //Throwing an error at programCS.OnTimedEvent()
}
}
And this is what I'm trying to call
class Program {
private static void Main(string[] args) {
SearchProcesses sP = new SearchProcesses();
sP.BuildProcessLists();
Console.WriteLine("Press Enter to exit the program...");
Console.ReadLine();
}
public static void OnTimedEvent(Object source, ElapsedEventArgs e) {
Console.WriteLine("Event was raised at {0}", e.SignalTime);
}
}
Please advise :)
Change
aTimer.Elapsed += ElapsedEventHandler(programCS.OnTimedEvent());
to
aTimer.Elapsed += ElapsedEventHandler(programCS.OnTimedEvent);
You are invoking programCS.OnTimedEvent, rather than passing it as a reference (and invoking it without arguments), thus the error.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm making C# application for click links of a webpage. But I want to do it with time interval. I mean link must click one second after another after next, like that. I make it but it click all links without time interval. I want to get all the links only onetime and click with interval. If I use timer class it will get links every time it elapse.
Here is my C# code. I tried different ways but none of them was success. Can u help me?
public void linkinvo()
{
int clickedobj = 0;
HtmlElementCollection elems = webBrowser1.Document.GetElementsByTagName("A");
for (int i = 0; i < elems.Count; i++)
{
String inhref = elems[i].GetAttribute("href");
String innerdoc = elems[i].InnerText;
textBox2.AppendText(inhref + " -->" + innerdoc + Environment.NewLine);
Thread.Sleep(1000); //i know this is not work
/* I want to run if part of this method with 1 second delay but not all the script */
if (innerdoc == "Like")
{
elems[i].InvokeMember("Click");
clickedobj = clickedobj + 1;
}
}
label3.Text = clickedobj.ToString();
Problem : You are not iterating the link execution process.
Solution :
Step 1: You need to take the Array of links to be executed.
Step 2: Subscribe to Timer Tick event.
Step 3: Set the Interval property of the Timer to 1000 milliseconds for raising the evnt for every 1 Second.
Step 4: In Tick Event Handler just invoke the next link from the LinkArray. and increment the linkExecutionCount variable.
Step 5: Repeat Step 4 untill linkExecutionCount reaches the Length of LinkArray.
Step 6: once if the linkExecutionCount Equals LinkArray length Stop the timer.
Try This: i have provided Sample Code on how to deal with mutilple Links
String [] LinkArray=new String[]{"link1","link2","link3"};
int linkExecutionCount=0;
System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer();
timer1.Interval=1000;//one second
timer1.Tick += new System.EventHandler(timer1_Tick);
timer1.Start();
private void timer1_Tick(object sender, EventArgs e)
{
if(linkExecutionCount == LinkArray.Length)
{
timer1.Stop();
}
else
{
//execute/open link
Open Link ---> LinkArray[linkExecutionCount]
//increment linkExecutionCount
linkExecutionCount++;
}
}
I worked on similar problem multiple times
I would suggest to use timer, you can always stop it, so it wont loop
after you will stop it, thus the part you need to run after 1 second should be in
(let say) timer 1, and if there is another 3rd link then start timer 2 from timer 1
them immediately in next line, stop timer 1, thus timer 1 will handle first link click
then it will start timer 2, and after starting timer 2, timer 1 will stop
I would highly recommend as per my experience with controlling actions in win forms
with browser control
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
To put it simply,
I start running my C# program in the morning, and the program should show the user a message at 5:45 PM. How can I do this in C#?
Edit: I asked this question because I thought using a timer is not the best solution (comparing the current time periodically to the time I need to run the task):
private void timerDoWork_Tick(object sender, EventArgs e)
{
if (DateTime.Now >= _timeToDoWork)
{
MessageBox.Show("Time to go home!");
timerDoWork.Enabled = false;
}
}
I asked this question because I thought using a timer is not the best solution (comparing the current time periodically to the time I need to run the task)
Why? why not timer a best solution? IMO timer is the best solution. but not the way you have implemented. Try the following.
private System.Threading.Timer timer;
private void SetUpTimer(TimeSpan alertTime)
{
DateTime current = DateTime.Now;
TimeSpan timeToGo = alertTime - current.TimeOfDay;
if (timeToGo < TimeSpan.Zero)
{
return;//time already passed
}
this.timer = new System.Threading.Timer(x =>
{
this.ShowMessageToUser();
}, null, timeToGo, Timeout.InfiniteTimeSpan);
}
private void ShowMessageToUser()
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(this.ShowMessageToUser));
}
else
{
MessageBox.Show("Your message");
}
}
Use it like this
SetUpTimer(new TimeSpan(17, 45, 00));
You can use Task Scheduler too.
Also there is a Timer class which can help you
You may easily implement your own alarm class. To start with, you may want to check the Alarm class at the end of the MS article.
You can use a Timer to check each minute if DateTime.Now == (the specific time you want)
This is an example of a code with windows forms
public MainWindow()
{
InitializeComponent();
System.Windows.Threading.DispatcherTimer timer_1 = new System.Windows.Threading.DispatcherTimer();
timer_1.Interval = new TimeSpan(0, 1, 0);
timer_1.Tick += new EventHandler(timer_1_Tick);
Form1 alert = new Form1();
}
List<Alarm> alarms = new List<Alarm>();
public struct Alarm
{
public DateTime alarm_time;
public string message;
}
public void timer_1_Tick(object sender, EventArgs e)
{
foreach (Alarm i in alarms) if (DateTime.Now > i.alarm_time) { Form1.Show(); Form1.label1.Text = i.message; }
}
UPDATE: I've managed to fix my problem. Using the code below, I moved my MessageBox AFTER my XML saving and changed the Timer from 100ms to 400ms. I now have 1 box appear, thank god. Although If anyone has a short cut to updating a single value (ActReminded) in the List array(ActListTask), that'd be great to know.
I'm having a little issue with displaying the MessageBox. Show inside a timer without it spamming me. Here's the part of the code I've been working with:
public class ActiveTasks
{
//Properties here
}
public List<ActiveTasks> ActTaskList = new List<ActiveTasks>();
for (int i = 0; i < ListActive.Items.Count; i++)
{
if (DTime.Date == newDateTime.Date)
{
if (newDateTimeLeft.CompareTo(TimeSpan.Zero) <= 0 && ActTaskList[i].ActReminded != "true")
{
MessageBox.Show("!!!!");
ActTaskList.Add(new ActiveTasks()
{
ActTitle = ActTaskList[i].ActTitle,
ActDesc = ActTaskList[i].ActDesc,
ActDate = ActTaskList[i].ActDate,
ActTime = ActTaskList[i].ActTime,
ActStatus = ActTaskList[i].ActStatus,
ActReminded = "true",
ActRepeat = ActTaskList[i].ActRepeat
});
ListActive.Items.RemoveAt(i);
ActTaskList.RemoveAt(i);
XDocument XmlActTasks = GenerateActiveListToXML(ActTaskList);
}
}
}
I actually decided I may want to hold onto the reminder status, whether it has been shown or not as I wouldn't want a repeated reminder every time the program is opened. Since I don't know of a way to update an individual part of ActTaskList I just re-added it, and then deleted the original. This code manages to recognise that if it happens, it will change the reminder status from false, to true; after I've Ok'ed all the spam. So it will stop the MessageBox once I've managed to closed all the Messageboxes. However, it doesn't stop the spam. Would it be anything to do with the fact I've set the timer to 100ms? Or could their be an alternative way to make the messagebox appear without it being inside the timer?
The odds of the current time lining up exactly to the second what is happening in your loop is small. Why not treat newDateTime as a cut off point and just set a flag?
//Declare this outside of the loop
bool hasDisplayed = false;
//Inside the timer event handler
if (!hasDisplayed && DateTime.Now >= newDateTime)
{
hasDisplayed = true;
MessageBox.Show("!!!!!!!!!!!!!");
}
Can you do something like this?
Action message = () => MessageBox.Show("!!!!!!!!!!!!!"));
object lockOb = new object();
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
lock(lockOb)
if(null != message)
{
message();
message = null;
}
}
You say you've already tried a boolean indicating the message has already been shown, I'm assuming because the code probably looked like it did below.
void TimerLoop()
{
bool msgAlreadyShown;
if(!msgAlreadyShown)
{
MessageBox.Show("!!!!!!!");
}
// Other work in your timer function
}
The problem with that code is that the bool will be set to false each time the function is called by the timer. You haven't posted much code, but you've at least stated what you're trying to accomplish, a timer that checks if a reminder should be presented to the user.
I'm about to make some wild guesses about how you've put together your software, there's a good chance it's way off, but I hope it might point you in the right direction. You could have some sort of reminder class like this:
public class Reminder
{
string Message { get; set;}
DateTime Alarm { get; set; }
bool IsDismissed { get; set; }
}
I'm assuming you might want to have multiple reminders that can be checked for in the timer loop, so your timer loop could look something like:
private List<Reminder> _activeReminders; // A list of reminders
void TimerLoop(object s, ElapsedEventArgs e)
{
lock(_activeReminders)
{
var now = DateTime.Now;
foreach(var reminder in _activeReminders)
{
// only run this code if the time has passed and it hasn't already
// been shown
if(now.CompareTo(reminder.Alarm) >= 0 && !reminder.IsDismissed)
{
MessageBox.Show(reminder.Message);
reminder.IsDismissed = true;
}
}
}
}
This is a pretty naive implementation, since you probably don't want to hold onto the reminders for forever and the reminders are never removed from the _activeReminders list, but you essentially just need to add some sort of state to determine if the reminder has already been shown.
Of course, this isn't a complete example either, since I never new up the _activeReminders field or add anything to it, but I think this might help get the idea of what you need to do across. Also, you might not care about multiple reminders, and your timer code could look nothing like this. The main idea was to show you how you can keep track of the state of a reminder, and tailor it to your own code. The above was just an example.
Also, I haven't actually tested it, so treat it more like pseudocode than anything else. However, the logic is sound, and should it should only cause the message box to appear once.