Reputation: 73
I am creating a bot which shall excecute mouseclicks as long as the timer goes but not longer than this. Like leftmouseclick than for 387ms it should do/spam rightmouseclick and wait 10ms between each click of rightmouseclick
Now I am searching for a way to do/spam the rightmouseclick in a loop for some milliseconds (not in an interval!).
Like:
for(387ms)
{
doSomething(); // doSomething() is rightmouseclick in my case
wait(10ms);
}
Where doSomething() gets excecuted as much as possible inside the 387ms timeframe and the wait(10ms) shouldn't affect the time remaining like I think it would be when using Thread.Sleep(10)
Upvotes: 1
Views: 1797
Reputation: 6749
Here are two methods, TimeLoop
and TimeLoopAsync
that will loop an action for a specific amount of time at a specific delay. Take what you need from it but it will accomplish what you're looking for.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp3
{
class Program
{
static async Task Main(string[] args)
{
const int TotalTimeMS = 200;
const int DelayMS = 10;
TimeLoop(() =>
{
Console.WriteLine($"First {DateTime.Now.Ticks}");
}, TotalTimeMS, DelayMS);
await TimeLoopAsync(() =>
{
Console.WriteLine($"Second {DateTime.Now.Ticks}");
}, TotalTimeMS, DelayMS);
Console.WriteLine("Done");
Console.ReadKey();
}
public static void TimeLoop(Action action, int totalTime, int delay)
{
var futureTime = DateTime.Now.AddMilliseconds(totalTime);
while (futureTime > DateTime.Now)
{
action.Invoke();
Thread.Sleep(delay);
}
}
public static async Task TimeLoopAsync(Action action, int totalTime, int delay)
{
var futureTime = DateTime.Now.AddMilliseconds(totalTime);
while (futureTime > DateTime.Now)
{
action.Invoke();
await Task.Delay(delay);
}
}
}
}
//OUTPUTS
//First 636813466330097482
//First 636813466330207562
//First 636813466330317509
//First 636813466330427504
//First 636813466330537519
//First 636813466330647498
//First 636813466330757504
//First 636813466330867485
//First 636813466330977501
//First 636813466331087479
//First 636813466331197483
//First 636813466331307522
//First 636813466331417580
//First 636813466331527516
//First 636813466331637533
//First 636813466331747513
//Second 636813466331867481
//Second 636813466332197479
//Second 636813466332317508
//Second 636813466332427498
//Second 636813466332647472
//Second 636813466332757495
//Second 636813466332977526
//Second 636813466333087469
//Second 636813466333197468
//Second 636813466333417483
//Second 636813466333527481
//Second 636813466333757457
//Done
Upvotes: -1
Reputation: 1298
I guess while is more appropiate for this and you can call below function to get what you want.
public void TimerLoop(int ms)
{
var now = DateTime.Now;
while(DateTime.Now < now.AddMilliseconds(ms))
{
//do your stuff here
}
}
Upvotes: 3