Calling a method every x minutes
var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromMinutes(5);
var timer = new System.Threading.Timer((e) =>
{
MyMethod();
}, null, startTimeSpan, periodTimeSpan);
Execute specified function every X seconds
Use System.Windows.Forms.Timer.
private Timer timer1;
public void InitTimer()
{
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 2000; // in miliseconds
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
isonline();
}
You can call InitTimer()
in Form1_Load()
.
How to call a method every minute but take into account the time it takes for that method to process might take more than one?
Something like this should work. With the AutoReset
flag set to false, the timer will only fire once, after the specified interval
time. In the finally
block, we make sure to restart the timer countdown, waiting for the interval to elapse again.
var interval = TimeSpan.FromMinutes( 1 );
var timer = new System.Timers.Timer( interval.TotalMilliseconds ) { AutoReset = false };
timer.Elapsed += ( sender, eventArgs ) =>
{
var start = DateTime.Now;
try
{
// do work
}
finally
{
var elapsed = DateTime.Now - start;
if ( elapsed < interval )
timer.Interval = (interval - elapsed).TotalMilliseconds;
else
timer.Interval = TimeSpan.FromSeconds( 30 ).TotalMilliseconds;
timer.Start();
}
};
timer.Start();
Source for Timer.Elapsed
(note the bit about setting Interval
resetting the countdown)
Python call a function every x minutes
I can't be 100% sure what you're trying to ask since your sample code currently has incorrect indentation.
I am assuming you mean something like this:
import time
wait = 10
for i in range(wait):
wait -= 1
time.sleep(1)
print(wait)
If you simply remove the time.sleep(1), the delay will no-longer occur while counting down. This should work:
wait = 10
for i in range(wait):
wait -= 1
print(wait)
[Edit]
Ah, thank you so much for the clarification! I believe this is what you're looking for:
import time
while True: # Here is your while loop!
wait = 10 # Change this to 900 (seconds) to get 15 minutes.
for i in range(wait+1):
print(wait)
wait -= 1
time.sleep(1) # Delay for one second.
print("Send email here!")
[Double-edit]
Oh, you would like to have sending emails not block the main section of your program! What @kenny-ostrom said would be correct here, then, you'd like to use threading in some way. Here's an example of sending an email every 15 minutes or 900 seconds. This happens in the background and whatever the while loop is doing is NOT blocked or delayed. This should be what you're looking for. c:
import threading, time
def send_my_email():
while True:
time.sleep(3) # Every 15 minutes is 900.
print("Send email now saying: {}".format(email_content))
thread = threading.Thread(target=send_my_email)
thread.start()
# Make a background thread and use the function: send_my_email
while True:
# Do anything here. No delays will happen.
for number in range(10, 0, -1):
print(number)
email_content = number*3 # You can modify email content here.
time.sleep(1)
How to call a method every x seconds for x time in Xamarin Forms?
You could set a limit seconds for the Timer.
For example you want do something every 5 seconds for 2 minutes.
int sec = 120000; // 2 minutes
int period = 5000; //every 5 seconds
TimerCallback timerDelegate = new TimerCallback(Tick);
Timer _dispatcherTimer = new System.Threading.Timer(timerDelegate, null, period, period);// if you want the method to execute immediately,you could set the third parameter to null
private void Tick(object state)
{
Device.BeginInvokeOnMainThread(() =>
{
sec -= period;
if (sec >= 0)
{
//do something
}
else
{
_dispatcherTimer.Dispose();
}
});
}
I want to run a method every minute that's started from my OnAppearing(). Do I need to run this as a task?
You can do this simpler by returning the correct value from Device.StartTimer
, to repeat true
, to not repeat false
and not use a StopWatch
. (source states that While the callback returns true, the timer will keep recurring.
And as you see from the source, the method doesn't need a Func<Task<bool>>
it only needs a Func<bool>
callback so there is no need to use a Task
.)
in the class
volatile bool run;
in OnAppearing
run = true;
Device.StartTimer(new TimeSpan(0, 1, 0), () => {
if (run) { /*do what you want;*/ return true; }
else { return false; }
});
in OnDisappearing
run = false;
EDIT - as requested by OP
Here is the code. I am leaving my original answer to help anyone else who needs this.
volatile bool run;
protected async override void OnAppearing()
{
base.OnAppearing();
BindingContext = vm;
cts = new CancellationTokenSource();
if (Settings.mode == MO.Practice)
{
run = true;
Device.StartTimer(new TimeSpan(0, 1, 0), () =>
{
if (run)
{
if (App.DB.ReducePoints() == true)
Device.BeginInvokeOnMainThread(() =>
{
vm.PifInfo = GetPifInfo();
});
return true;
}
else { return false; }
});
await GetCards(cts.Token);
}
}
protected override void OnDisappearing()
{
run = false;
Unsubscribe();
cts.Cancel();
base.OnDisappearing();
}
Call method once every 5 minutes
You could simply create a timestamp when your class is instantiated (in the constructor).
Your send method simply checks "more than 5 minutes since that timestamp"?
If yes: then take a new timestamp, and send the mail.
If no: do nothing.
That's all you will need. Not going to provide code here, as this is probably homework, and the point is that you learn how to write the corresponding code.
Related Topics
How to Show the "Paste JSON Class" in Visual Studio 2012 When Clicking on Paste Special
Does Disposing Streamreader Close the Stream
How to Ignore JSONproperty(Propertyname = "Somename") When Serializing JSON
What Does Null! Statement Mean
Can a C# Thread Really Cache a Value and Ignore Changes to That Value on Other Threads
Most Efficient Way to Remove Special Characters from String
Detect Target Framework Version at Compile Time
How to Create/Edit a Manifest File
How to Convert Struct System.Byte Byte[] to a System.Io.Stream Object in C#
How to Use Linq Contains(String[]) Instead of Contains(String)
How to Convert a Gi-Normous Integer (In String Format) to Hex Format? (C#)
Http Error 500.30 - Ancm In-Process Start Failure
Random Number Generator with No Duplicates
Why Can't I Have Abstract Static Methods in C#
Random String Generator Returning Same String
How to Get the Calling Method Name and Type Using Reflection
Unrecognized Escape Sequence for Path String Containing Backslashes