Welcome guest. Before posting on our computer help forum, you must register. Click here it's easy and free.

Author Topic: Neat way of knowing where PING as a timer is in its time delay with color  (Read 2912 times)

0 Members and 1 Guest are viewing this topic.

DaveLembke

    Topic Starter


    Sage
  • Thanked: 662
  • Certifications: List
  • Computer: Specs
  • Experience: Expert
  • OS: Windows 10
Sharing a neat way to know how close a PING time delay is to triggering event by Color.

I use one of my computers for browser based games and the part of the games where they expect people to sit at their computer and wait for:

5 minutes
15 minutes
1 hour
4 hours
8 hours
24 hours
or
48 hours

For a process (timer) to complete before you can gather whatever it is that you are farming/making etc is more boring than watching paint dry. So I have created keyboard/mouse macros and added them to simple batch files to run in time delay loops.

Prior to last night, I had to quickly close the batch execution of a PING to 127.0.0.1 as a time delay before triggering a EXE to run the keyboard/mouse macro, when wanting to use the computer for other than the automated process, and  sometimes right as I go to close it it triggers the EXE because I wasnt aware that it was about to trigger before using keyboard and mouse, and then when the macro starts I have to wait for the macro to do its thing as for keyboard and mouse are no longer in control until it ends.

I was thinking there has to be a way to know how close to triggering the PING time delay is in my batch, then had the idea of changing background color at 3 intervals. One color GREEN to be for the longer time delay, then YELLOW for the time delay that is shorter duration but I know I have time if I want to do something quick with computer without the macro triggering when I am using the system, and RED for warning that there is very little time left in the time delay sequence before the batch triggers the Macro and then loops back to beginning back to first time delay.

So I have the following

Code: [Select]
:loop
color 3f
ping 127.0.0.1 -n 520
color e0
ping 127.0.0.1 -n 300
color 4f
ping 127.0.0.1 -n 120
trigger.exe
goto loop

This gives me a little beyond 15 minutes of time delay before triggering a macro that gathers a virtual product and then starts the new creation of virtual product. So that I can just play the fun part of the game strategy and combat and all that and not have to deal with the material creation and gathering grind, and now I can look at the window and know how close to triggering the batch is to triggering the macro.

Figured I'd share this in case others even needed a creative way of knowing how close a time delay by use of PING was before triggering by use of the color xx instruction before each time delay of tiered delays that make up a whole delay.

Its nice being able to do other stuff that is more important and have the game played automated while at work, sleeping, or doing basically anything else other then the boring farming process. I use my electron sipper computer that runs on about 40 watts of power to do this too and this way electric bill is small for a computer that runs 24 hours a day to perform mostly automated redundant processes.  ;D

BC_Programmer


    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
I find that when I need these sorts of things I'll usually write a C# program for the task. I also use it to resolve Annoyances i have with Windows, such as how they made the network foldout rather silly in Windows 10.

That said, for stuff like this I usually just write a program for the learning experience and because it gives me a problem to program a solution to, rather than because I really need that solution. (in that case it's ping all the way).

With that in mind I thought I'd tackle your "problem" in that way. A fairly short thrown-together program that you give a timeout like 00:00:20 for 20 seconds, and it reports every 10th of the way through. Though in the interest of making things interesting I'll write it in Visual Basic .NET. It can change colors but with 10 offset reports I don't know how useful colour coding could be, so I left that out:

Code: [Select]
Module ConWaiter

    Sub Main(Arguments As String())
        'ConWaiter program waits a specified amount of time.
        'it displays messages showing progress at certain times as well.
        'arguments: ConWaiter <time>
        If Arguments.Length>0 Then

            Dim TimeWait As TimeSpan
            TimeSpan.TryParse(Arguments(0),TimeWait)
            Dim ReportOffsets As New Queue(Of TimeSpan)
            ' report every 10th increment.
            'obviously this will be really odd and strange for rather small increments. Nevermind that.
            'Dim Offset As Double

            For Offset As Double = 0.10# to 0.9# Step 0.1#
                ReportOffsets.Enqueue(new TimeSpan(TimeWait.Ticks*Offset))
            Next

            Dim sw As New Stopwatch
            sw.Start()
            Console.WriteLine("Waiting for " + TimeWait.ToString())
            Do while sw.Elapsed < TimeWait

                If ReportOffsets.Any() Then
                    'check for an offset.
                    Dim nextOffset = ReportOffsets.Peek()
                    If sw.Elapsed > nextOffset Then
                        Console.WriteLine((TimeWait-sw.Elapsed).ToString() + " Remaining.")
                        ReportOffsets.Dequeue()
                    End If
                End If

            Loop
            Console.WriteLine(TimeWait.ToString() + " Has elapsed.")
        Else
            Console.WriteLine("Time to wait not specified.")
        End If

    End Sub

End Module

Ideally it would be a GUI program, tbh- maybe showing the "Time to Execute" all the time for example, like a countdown.
I was trying to dereference Null Pointers before it was cool.

DaveLembke

    Topic Starter


    Sage
  • Thanked: 662
  • Certifications: List
  • Computer: Specs
  • Experience: Expert
  • OS: Windows 10
Just got back and saw what you posted here. Thanks for taking the time to code this up. Going to check it out when I get home from work tonight.

I was thinking about a timer that would display a count down to give better representation of actual time left etc. The batch method with the color command was a down and dirty approach just to have some sort of indication as to if its safe to start using the keyboard/mouse and know its green so I have plenty of time to check on something or its yellow so I have greater than 2 minutes to check on email etc, or red in which I should leave it be for up to 2 minutes and let it perform its automated instruction.

Quick look at your code .. it looks like your not triggering an EXE from within the timer or maybe im blind  ;D ... so calling to an EXE to run from within your code... would then go with a "system call"? or would you go with this countdown program in batch loop so when count down is up it simply ends the count down program and the next line is to run the macro EXE and when the macro ends its sent back via GOTO into a batch loop to start the count down timer again and repeat until the batch is terminated?, or is there a better method than nesting this into a batch loop (or) system call within the code to run the macro EXE before starting the count down timer again all within the program itself and no batch and no system calls?

I have always used "system calls" in languages i work with within my code to trigger to run other programs, so curious how this might be done without a system call if there is a way. Or if Its one of the 2 other methods in which its a system call within the count down timer or the count down timer is only a count down timer and placed within a batch script loop you can have it loop back to timer, macro, loop back to timer and so on....  :)

BC_Programmer


    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
The idea would be to use it in a batch file as a way of showing a indicator of the time lefty at intervals, then it returns and the batch file would execute the program and start over.
I was trying to dereference Null Pointers before it was cool.

DaveLembke

    Topic Starter


    Sage
  • Thanked: 662
  • Certifications: List
  • Computer: Specs
  • Experience: Expert
  • OS: Windows 10
Cool thanks for clarifying  and your help with this.  :)

DaveLembke

    Topic Starter


    Sage
  • Thanked: 662
  • Certifications: List
  • Computer: Specs
  • Experience: Expert
  • OS: Windows 10
Got bored ... down with the flu and decided to make a count down from scratch with color in C++.

One annoyance was that the timer would get below 10 seconds and show 9,8,7 ... vs 09, 08, 07 and so I put in a conditional output to add the leading 0

Initially I did this with a char zero; and then IF, Then logic to have <<zero<< before the <<seconds<< and have a char output of '0' or ' ', but this caused an annoying character space shift by 1 character place to the left when it went from double digits to single second digits. Additionally the compiler warned me of use of ' ' as it didnt see the space in between ' ' as a space to use.

Looking back I suppose I could have called to the ascii character for space by calling to hex of 0x20 with unsigned char. But I went the easy route on this to just have an alternate output based on if the seconds were less than 10.

Additionally the more that is happening in the program the more latent the timer would be  since while sleep is set to 1000ms, everything else that is going on in the loop makes it very slightly latent to getting back to the sleep condition so I wanted to keep it as small and uncomplex as possible to reduce latency in the timer as a result of everything that goes on per iteration.

I havent set a stop watch side by side this yet to see if the latency builds to any noticeable offset, but depending on the processor that runs this, the weaker the CPU, the more noticeable the latency would build vs a faster CPU that would plow through the logic and wait at the 1000ms timer with less latency. I suppose if I saw a difference and wanted greater precision I could adjust the sleep to say 990ms if the rest of the program takes 10 ms etc to be as close as I can to 1000ms.

I was going to call to the macro from within the program, but macro naming would change, and I dont want to recompile for each different macro name or have to stick with specific macro names, so I will use this within a batch loop.

I went with 6 minutes on this timer because the process takes 5 minutes to complete and I wanted to add an extra minute of time before it carries out the macro process. In the past I have run into problems with race conditions when setting a timer to close to how long a process actually takes and so a minute of idle time every 5 minutes is fine and only amounts to the difference of this running 10 times an hour vs 12 times an hour, but at 10 times per hour I know that I wont have a malfunction from a race condition between timer of this automated process and timer of the game.

Code: [Select]
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;

int main()
{
   
    // 6 minute Time Delay with count down
    long long int time=360;
    int minutes;
    int seconds;
    cout<<"6 Minute Timer ... Count Down = [ 6 : 00 ]"<<'\r'<<flush;
    while(time>0)
    {
              if (time>=360){
                            system("Color A");
                            }
                            else if (time<180 && time>60){
                                        system("Color E"); 
                                        }
                                        else if(time<60){
                                               system("Color C");
                                               }
        Sleep(1000);
        time--;
        system("CLS");
        seconds=time % 60;
        minutes=time/60;
        if (seconds<10){
        cout<<"6 Minute Timer ... Count Down = [ "<<minutes<<" : 0"<<seconds<<" ] "<<'\r'<<flush;
                        }
                        else {
        cout<<"6 Minute Timer ... Count Down = [ "<<minutes<<" : "<<seconds<<" ] "<<'\r'<<flush;
                             }
    }
    cout<<"End Timer"<<endl;

    return 0;
}





BC_Programmer


    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
Since you are importing conio.h, you may as well use the clrscr() function instead of system("cls") :P

of course conio.h is iirc Windows only- and it's "C" rather than the "C++ way" . Realistically you shouldn't be clearing a console window anyway, to be fair. At "worst" programs like chkdsk for example will set the position and overwrite text (eg chkdsk's progress display). I thiink the idea is to preserve the console buffer, rather than "take control" of it if that makes sense. Of course in a program for your own use it's not going to matter, I suppose.


for your leading zero formatting issue, you can use iomanip which is part of the standard C++ library. Something like this:

Code: [Select]
include <iomanip>
using namespace std;
...

for(int i=10;i>0;i--)
    cout << setfill('0') << setw(2) << i

For timing my example records a start time and waits until the difference between the current time and that start time reaches the desired amount, eg. somethiing like this should wait 5 minutes:

Code: [Select]
startclock = std::clock();
while( (60*5) > (duration=(clock() - startclock ) / (double) CLOCKS_PER_SEC))
{

//do stuff, can check duration to see the current time that has elapsed for example and show counters

}

Of course it could still "overlap" and not be precisely on time due to the last iteration taking longer- for example if you add a sleep(500) into the loop it could be as much as 499ms "late" but you wouldn't usually add a sleep with a tiime offset. usually you'd use sleep(0) to yield control to other threads while waiting.

I actually started a program to do something like this because it is an interesting concept and I couldn't really find a program for the purpose; Task scheduler is similar but designed for a more hands-off use, and you can't really see tasks it runs as it runs them, how long until the next one is run, etc. updated in real-time. My thinking is rather than a console program it would be a standard desktop application controlled via a GUI. You would create a series of... Tasks? DelayItems? Repeaters? Not sure a good name for them that isn't confusing, with the appropriate information- the command line and arguments, the time delay between invokations, etc. And then when it is all configured you could start, pause, reset, etc the items in the list, all of which would show a nice little progress bar to their next invocation. Something like this:


This is the Update program I created for our (my companies) software deployments... (well it's based on a program I wrote about 7 years ago) My thinking is something like the progress bars it uses, but showing the "progress" to the next invoke, with a drop down to pause, stop, reset, or edit (command line, arguments, the time delay, etc)  each item when right clicked. The progress bar would say say "10% 9:00 left" and count down for each one, then when it got to 100% it would change to "Running Task" and the Task it was set to run would be invoked, and when it returned control the program would reset everything for another cycle. Paired with minimizing to the Notification Area and (optionally) showing balloons/notifications when it runs a task, it could be a useful general purpose program for when you want to run stuff at an interval and want to be able to see easily when things will be run next and how long until the next one runs.
I was trying to dereference Null Pointers before it was cool.

DaveLembke

    Topic Starter


    Sage
  • Thanked: 662
  • Certifications: List
  • Computer: Specs
  • Experience: Expert
  • OS: Windows 10
Hey BC... very cool and yes... its a mix of C and C++ now that I look back at it.  ;D  Back in the days of Qbasic I use to mix Basic with QBasic too as it had legacy Basic support.

Thanks for pointing out
Quote
clrscr() function instead of system("cls")

I got lazy trying to remember the clear screen function and said ok just use a system call to cls  ::)

Very cool use of iomanip for the leading zero correction. I forgot about iomanip's ability to format this way. Back in college I used it mainly for dealing with money where I'd be programming up point of sale type of programs and the get_money and put_money was used with iomanip. Going to add your correction to my program to get rid of the alternate IF logic for alt output when value less than 10.  8)

As far as use of std::clock(); ... I actually avoided use of it because I thought it might be more difficult to get the precision for time delay and it looks like it taxes the CPU whereas sleep is less on the CPU. I read up on this article below on troubles with its use in which mainly depending on how powerful or weak of a CPU your running, the results will vary in how fast or slow the time delay is. So I figured a safer approach might be to just go with sleep() and set that to 1000ms and this way I am right in the ballpark at the get go and might just need to reduce from 1000ms to another lesser value after running it along side a clock or stop watch to see if the second intervals are somewhat sync. Running it today I see that its out of sync and might be as far out of whack as 1.2 seconds per 1 second. With this count down timer being slower (taking longer) to count down from 6 minutes.

http://stackoverflow.com/questions/35439992/stdclock-and-clocks-per-sec

To have an idea of how long it takes for time delay and the macro process, in the batch file I had added appending of date/time stamp into a log file so i see when the timer starts, when the timer ended, and when the macro ended before the timer starts again.

The system that I have running this is a weak electron sipper Intel Atom N280 single-core with Hyperthreading 1.66Ghz running Windows XP SP3 on 2GB RAM which runs consuming just 13 watts of power. Its barely able to run the flash game and is so laggy that no one in their right mind would ever have the patience to game with it, but the automated process is not painful for a human to endure and so i gave this otherwise modern flash game crippled netbook a purpose and its holding up well to it.

Other system I am running for the automated farming with a keyboard/mouse macro is the Sempron 3850 1.3Ghz Quadcore 4GB DDR3 running Windows 7 64-bit which runs on about 43 watts of power.

So the programming methods have to be as CPU friendly as I can make them. The 1.3Ghz Quadcore holds up really well, but the clock of 1.3Ghz for single-threaded program means that while this system is generally better than the Intel Atom, the Intel Atom might actually be faster at the single-threaded C++ program execution due to the 1.66Ghz clock.

Thats really cool that you found a purpose for the program you made 7 years ago for your work. If I had a bunch of different macros triggering at different times, then something like that would be cool to see what was last to run and whats next to run etc.

Hopefully when I share code its not painful as nails to a chalk board to see abstract or blended coding methods.  ;D My college professor told me once that they should have a Rube Goldberg award to issue once a year to the most oddest of programming programmers, because he would have given it to me. Compiled the program runs as intended and without flaws and most wouldnt know how strangely constructed it was. But another programmer looking at the source code they generally are like  :o and  ::) ha ha ha ... I do try to better my programming methods though and so I welcome all feedback. Thank you for your help and suggestions.  :) I think some of my problems with coding is that I have dabbled in so many different languages as programming as a hobby and at times there becomes a blend. Such as the C within the C++ etc. Since if it compiles without any issues... And runs as intended, then all is good  ;D :P


BC_Programmer


    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
Yes, I see I was mistaken on what Clock() actually does. It records actual CPU time used by the process and isn't the equivalent of the more common "number of milliseconds since midnight". So timing it would probably need something like time.h.

If you use an "idle loop" where you call sleep(0) to yield control within a tight loop waiting for a time to elapse, CPU usage is fairly low. It can be lowered still by using larger sleep() times as well.

As  far as Code style/good practices are concerned, I'd be lying if I said I didn't put my hands up and say "whyyyy" once or twice with some of your samplings :P. Though I've done the same with my own code as well. It's  mostly a thing for future maintainability, so maybe doesn't affect small programs quite as much. The Program I used in that picture is about 20K lines of code across 48 files- which is certainly approaching "non-trivial". In addition to having to pop it open a few months later when we want to add some new feature or capability, or investigate an issue that was reported, it might not always be me doing so. maybe I'm on vacation or unavailable- like maybe during a deployment late at night there is some issue and I'm not around, or maybe I took time off or whatever. Which means that sometimes one of my co-workers needs to pop it open and take a look see, so it has to be fairly readable and understandable. That applies to all our software and I try to apply it to my own programs as well- Even if nobody else is really going to look at or modify it, I am, and looking at it a year later I may as well be somebody else entirely. a simple program could easily evolve into something much larger so writing it "clean" from the start is usually a good idea.

I was trying to dereference Null Pointers before it was cool.

DaveLembke

    Topic Starter


    Sage
  • Thanked: 662
  • Certifications: List
  • Computer: Specs
  • Experience: Expert
  • OS: Windows 10
Quote
Even if nobody else is really going to look at or modify it, I am, and looking at it a year later I may as well be somebody else entirely. a simple program could easily evolve into something much larger so writing it "clean" from the start is usually a good idea.

 ;D So I am not alone in sometimes looking at own source code from the past at times ... and " I may as well be somebody else entirely"... I have had some projects of the past that I am like ok I need to print the source out and take colored pencils to it and notate what is going on... especially if I didnt put in comment lines to make future readability easy.  ::) Lots of times I program and its just a direct brain dump of what needs to be coded up without adding comments as to why. And most programs they compile and run and I never revisit them, but on the rare occasion that I revisit a program from say 2 or more years ago, I have also said "Whyyyyy" to myself as to why I went with a specific way of doing it when reading it years later once I am able to follow it again, I sometimes realize that I over thought the code and really should have K.I.S.S method ( Keep It Simple Stupid )  ;D Such as multiple lines that do the same thing and I really should have coded in reuse of functions vs making so many functions that function the same, so remove all those redundant functions an instead call to the function making for better code, and if say that function needed to be revised, its just that one function and not having to track down the 6 functions that do the same thing that all would need the change with the chance that I could miss one and now have a program that compiles and under certain conditions there is a legacy function triggering vs the most up to date instructions.  ;)

Thanks for your help with this BC and cool and well skilled approach to all of this.  8)