I need to perform an action every day after September 5. I wrote this program
#include <windows.h>
int main()
{
SYSTEMTIME time;
GetLocalTime(&time);
if((time.wMonth = 9 && time.wDay >= 6) || time.wMonth > 9)
{
//perform action
MessageBox(GetForegroundWindow(), "Action performed. Month is " + std::to_string((long long)wMonth), "Alarm!", MB_OK | MB_SYSTEMMODAL);
}
}
I ran this program and the message box displays. But today is August 22, I checked my computer's clock. What am I doing wrong?
Reference SYSTEMTIME
Update:
After writing this question I checked the values of wMonth and wDay and these are 1 and 22, i.e. Jan 22.
Seems like a bug. What do I do to get correct month?
if((time.wMonth = 9 ... needs to be :
if((time.wMonth == 9 ...
^^^^
If you reverse your test (and many C++ programmers do), the compiler will emit an error :
if((9 = time.wMonth ... // error !
Which is a way of catching this frequent typo.
I think is better to use the cron manager (Linux) or Task Manager (Windows) to schedule your job
Related
I'm quite new in the opcua's world and I'm trying to monitor a server variable with a client in C++.
I'm on the 1.2.2 version of opcua
I have a boolean variable in the server at the node (1,6070) and when I run the following code I receive the LOG :
[2021-08-03 15:27:47.442 (UTC+0200)] info/session Connection 5 | SecureChannel 2 | Session ns=1;g=913a21de-f467-5bc9-ed9e-29b27b470490 | Subscription 2 | Created the Subscription with a publishing interval of 500.00 ms
But I've never reach the function 'handler_events_datachange' in which I only put an output for now. (I'm sure that the value in the node 6070 changed btw)
Thanks for helping!
int main(void) {
signal(SIGINT, stopHandler); /* catches ctrl-c */
UA_Client *client = UA_Client_new();
UA_ClientConfig *cc = UA_Client_getConfig(client);
UA_ClientConfig_setDefault(cc);
UA_Client_connect(client, "opc.tcp://localhost");
UA_MonitoredItemCreateResult result;
UA_CreateSubscriptionResponse response; // warning memory leak
UA_CreateSubscriptionRequest request = UA_CreateSubscriptionRequest_default();
UA_Client_Subscriptions_create(client, request, NULL, NULL, NULL);
UA_Int32 subId = response.subscriptionId;
if(response.responseHeader.serviceResult == UA_STATUSCODE_GOOD)
{
UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND , "subscription succed");
} else {
UA_LOG_ERROR(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND , "subscription UNsucced");
}
UA_MonitoredItemCreateRequest monRequest = UA_MonitoredItemCreateRequest_default(UA_NODEID_NUMERIC(1, 6070));
result = UA_Client_MonitoredItems_createDataChange(client, subId, UA_TIMESTAMPSTORETURN_BOTH, monRequest, NULL, handler_events_datachange, NULL);
while(running) {
}
}
I finally found the error !
The problem comme from the fact no means of handling asynchronous
events automatically is provided. However, some synchronous function
calls will trigger handling, but to ensure this happens a client
should periodically call UA_Client_run_iterate explicitly.
So the solution is to add UA_Client_run_iterate(client,100) in the while().
I didn't fully understand what the timeout was about but I'll complete this answer if I can
I am testing application's latency during UDP communication on windows 10.
I tried to send a message every 1 second and receive a response sent immediately from the remote.
Send thread
It works every 1 second.
auto start = std::chrono::system_clock::now();
unsigned int count = 1;
while (destroyFlag.load(std::memory_order_acquire) == false)
{
if (isReady() == false)
{
break;
}
/*to do*/
worker_();
std::this_thread::sleep_until(start + std::chrono::milliseconds(interval_)* count++);
}
worker_()
Send thread call this. just send message and make log string.
socket_.send(address_);
logger_.log("," + std::string("Send") + "\n");
Receiver
When message arrives, it creates a receive log string and flushes it to a file.
auto& queueData = socket_.getQueue();
while (queueData.size() > 0)
{
auto str = queueData.dequeue();
logger_.log(",Receive" + str + "\n");
logger_.flush();
}
I've been testing it overnight and I can't figure out why I got this result.
chart for microseconds
x-axis : Hour_Minute_second
y-axis : microseconds
For a few hours it seemed to work as expected. But after that, the time gradually changed and went to a different time zone.
Does anyone know why this is happening?
std::chrono::steady_clock is working.
It made my charts straight.
And another way, turn off the windows automatically time synchronize.
I am currently using the AWS IoT SDK for the Arduino Yun, and I am running the example sketches (specifically the Thermostat simulator).
I modified the loop slightly (just changed the delay at the end) such that it looks like this:
void loop() {
if(success_connect) {
// If the desired temperature is set to a higher value, start heating.
if(desiredTemp - reportedTemp > 0.001) {reportedTemp += 0.1;}
// If the desired temperature is set to a lower value, start cooling.
else if(reportedTemp - desiredTemp > 0.001) {reportedTemp -= 0.1;}
dtostrf(reportedTemp, 4, 1, float_buf);
float_buf[4] = '\0';
sprintf_P(JSON_buf, PSTR("{\"state\":{\"reported\":{\"Temp\":%s}}}"), float_buf);
print_log("shadow update", myClient.shadow_update(AWS_IOT_MY_THING_NAME, JSON_buf, strlen(JSON_buf), NULL, 5));
if(myClient.yield()) {
Serial.println("Yield failed.");
}
delay(10000); // CHANGED TO 10 SECONDS INSTEAD OF 1
}
}
For some reason, when the loop is delayed for less than 10 seconds, the shadow update has no problem repeating. But as soon as the delay is 10 seconds or more, I get this error:
Exception in thread Thread-4 (most likely raised during interpr
[ERR] command: shadow update code: -1
I changed the CMD_TIME_OUT to a higher value in the aws_iot_config_SDK.h file, but it still seems to have no effect. The reason why I'd like the timeout delay to be larger than 10 seconds is because I want to ideally have a trigger mechanism in the arduino that would update the shadow.
On Mac OS X, using C and/or C++, I want to change the creation time of a file to an arbitrary date/time. I have found a number of solutions, notably this StackOverflow answer, that allow to set the creation time to an older date, but this is not sufficient for me - I also want to be able to set a newer date. Using the utimes() function therefore is not the solution I am looking for.
I know that setting a newer creation time must be possible somehow, because the SetFile utility from Apple's developer command line tools can do it, but so far my search-fu has failed to uncover any hints that bring me closer to a solution.
Does anyone know of a way how I can achieve my goal?
Why do I want to do this myself, why can't I use SetFile?
The SetFile command line utility is deprecated (see man SetFile), so it's bound to go away some time in the future
I want to create a utility that allows me to specify a time delta to add to/subtract from the current creation time. The SetFile utility does not have any convenient command line arguments to do this.
Last but not least: Curiosity!
Haven't tried it, but according to the docs, the NSURL resource value under the key NSURLCreationDateKey is read-write. Since you specified C or C++, you'd use the corresponding CFURL API. So, you'd call:
CFURLRef url = /* ... */
CFDateRef date = /* ... */
CFErrorRef error;
if (!CFURLSetResourcePropertyForKey(url, kCFURLCreationDateKey, date, &error))
/* handle error */;
EDIT: A minimal example
const char* fileName = "/path/to/file";
size_t fileNameStringLength = strlen(fileName);
Boolean isDirectory = false;
CFURLRef url = CFURLCreateFromFileSystemRepresentation(
kCFAllocatorDefault,
(const UInt8*)fileName,
fileNameStringLength,
isDirectory);
// Seconds since 1 January, 2001 00:00:00 GMT
CFAbsoluteTime absTime = CFAbsoluteTimeGetCurrent();
CFAbsoluteTime adjustedCreationTime = absTime - 3600;
CFDateRef date = CFDateCreate(
kCFAllocatorDefault,
adjustedCreationTime);
CFErrorRef error;
if (!CFURLSetResourcePropertyForKey(url, kCFURLCreationDateKey, date, &error))
{
fprintf(stderr, "an error occurred\n");
exit(1);
}
CFRelease(url);
CFRelease(date);
BTW, I have no idea if this is safe, secure, whatever. So, do this at your own risk.
On OS X, you can sort of do this by setting the time of the day to the future and then copying the file (and renaming it back). It is not the same file with its creation time modified; it is a copy with the creation time you set.
Some code (I got the code to set the time of the day from here):
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <copyfile.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
struct timeval tv_now, tv_set;
copyfile_state_t s;
struct stat st;
// retrieve original stat
if (stat(argv[2], &st) < 0)
perror("stat");
// get current time of day
if (gettimeofday(&tv_now, 0) == -1)
perror("gettimeofday");
// set time of day to +argv[1] days
tv_set = tv_now;
tv_set.tv_sec += 86400 * atoi(argv[1]);
if (settimeofday(&tv_set, 0) == -1)
perror("settimeofday to future");
// copy the file to a temporary, copy everythig except stat
s = copyfile_state_alloc();
if (copyfile(argv[2], ".eighty_eight_miles_per_hour", s, COPYFILE_ACL | COPYFILE_XATTR | COPYFILE_DATA) < 0)
perror("copy file");
copyfile_state_free(s);
// rename it back to original name
if (rename(".eighty_eight_miles_per_hour", argv[2]) < 0)
perror("rename file");
// restore file owner, group, and mode
if (chown(argv[2], st.st_uid, st.st_gid) < 0)
perror("chown");
if (chmod(argv[2], st.st_mode) < 0)
perror("chmod");
// reset current time of day
if (settimeofday(&tv_now, 0) == -1)
perror("settimeofday back to now");
return 0;
}
I call this program the flux_capacitor. The first command line argument is the number of days forward to set the file's creation date, and the second argument is the file name. You have to run this program as root to set the time.
Observe, as I send the delorean forward in time by 2 days.
[ronin:~/Documents/CPP] aichao% touch delorean
[ronin:~/Documents/CPP] aichao% ls -l delorean
-rw-r--r-- 1 aichao staff 0 Aug 10 11:43 delorean
[ronin:~/Documents/CPP] aichao% su
Password:
sh-3.2# ./flux_capacitor 2 delorean
sh-3.2# exit
exit
[ronin:~/Documents/CPP] aichao% ls -l delorean
-rw-r--r-- 1 aichao staff 0 Aug 12 2016 delorean
[ronin:~/Documents/CPP] aichao% date
Wed Aug 10 11:43:47 EDT 2016
and in the Finder:
Note that I only restore the original owner, group, and mode from the stat for the file. I don't think you can or want to do more than that, but I don't know. Obviously, links to the file will be broken.
I'm diving through ACE and, I'm logging message in a file using the ACE_ERROR macro.
And AFAIK, ACE_ERROR logs all the messages in the same file, regardless of their error level.
However, I actually need to write messages, according to their error level.
I did see the ACE_LOG_MSG->open() function however, what i understand is that when you already calling this function twice, the second time it will close the file you opened when you called the function at the beginning.
Suppose I have a list and I want to log it and, in this list, two adjacent items don't have the same error level.
Then I would be opening and closing files, wouldn't than affect my apps performance ?
So is there a way to keep those files open ?
Thanks !
Not closing the files you log to is particularly bad in debugging. If the application crashes with an open file, its contents may (and that happens rather often) get corrupted, leaving you with absolutely no information.
If you close the file properly, though, you're guaranteed to find at least some info there, possibly closer to the real issue. If you are concerned with performance, you should simply reduce log level, or if it's not feasible, you could perhaps offload the logging to the other process via (for example) TCP connection.
Anyway, don't optimize until you've measured! It might just be there'll be no impact, performance is a complicated problem which depends on lot of factors.
Another example to re-direct logging as per their logging priority, using a simple wrapper class.
Hope this is useful to someone.
Example program
#include "ace/Log_Msg.h"
#include "ace/streams.h"
// #Author: Gaurav A
// #Date: 2019OCT11
//
// Log each logging statement
// in file based on its priority
//
// eg: INFO logs goes to INFO.log
// DEBUG logs goes to DEBUG.log
class Logger
{
private:
ACE_OSTREAM_TYPE* m_infolog=nullptr;
ACE_OSTREAM_TYPE* m_debuglog=nullptr;
public:
Logger(void)
: m_infolog (new std::ofstream ("INFO.log")),
m_debuglog (new std::ofstream ("DEBUG.log"))
{
}
~Logger(void)
{
delete m_infolog;
delete m_debuglog;
}
int log (ACE_Log_Priority p,
const ACE_TCHAR* fmt,
...)
{
ssize_t final_result=0;
if (p == LM_DEBUG)
{
va_list argp;
va_start (argp, fmt);
ACE_LOG_MSG->msg_ostream (m_debuglog);
ACE_LOG_MSG->set_flags (ACE_Log_Msg::OSTREAM);
final_result = ACE_LOG_MSG->log (fmt, LM_DEBUG, argp);
va_end (argp);
}
else if (p == LM_INFO)
{
va_list argp;
va_start (argp, fmt);
ACE_LOG_MSG->msg_ostream (m_infolog);
ACE_LOG_MSG->set_flags (ACE_Log_Msg::OSTREAM);
final_result = ACE_LOG_MSG->log (fmt, LM_INFO, argp);
va_end (argp);
}
return final_result;
}
};
int
ACE_TMAIN (void)
{
Logger logger;
logger.log (LM_DEBUG, "I am a debug message no %d\n", 1);
logger.log (LM_INFO, "I am a info message no %d\n", 2);
logger.log (LM_DEBUG, "I am a debug message no %d\n", 3);
logger.log (LM_INFO, "I am a info message no %d\n", 4);
return 0;
}
Sample Output
[07:59:10]Host#User:~/acedir
$: ./logging_each_priority_in_its_own_file
I am a debug message no 1
I am a info message no 2
I am a debug message no 3
I am a info message no 4
[07:59:10]Host#User:~/acedir
$: ls -lrth
total 464K
-rw-r--r-- 1 aryaaur devusers 231 Oct 11 07:09 logging_each_priority_in_its_own_file.mpc
-rw-r--r-- 1 aryaaur devusers 5.6K Oct 11 07:29 GNUmakefile.logging_each_priority_in_its_own_file
-rw-r--r-- 1 aryaaur devusers 1.5K Oct 11 07:47 main_logging_each_priority_in_its_own_file_20191011.cpp
-rwxr-xr-x 1 aryaaur devusers 65K Oct 11 07:47 logging_each_priority_in_its_own_file
-rw-r--r-- 1 aryaaur devusers 50 Oct 11 07:59 INFO.log
-rw-r--r-- 1 aryaaur devusers 52 Oct 11 07:59 DEBUG.log
[07:59:10]Host#User:~/acedir
$: cat INFO.log
I am a info message no 2
I am a info message no 4
[07:59:10]Host#User:~/acedir
$: cat DEBUG.log
I am a debug message no 1
I am a debug message no 3
[07:59:10]Host#User:~/acedir
$: