此代码只能运行一次,即如果用户联机并脱机。我想以这样的方式循环,它始终为我提供信息。如:在线11:00,离线11:30,在线11:45,离线12:00。
我该如何解决?
bool showed =false;
bool nshowd =false;
for (; ; )
{
//chech_online() <- this methods gives true if the person is online on FB
bool check_online =check_online();
if(check_online ==true && !showed)
{
Console.WriteLine("Online !!" +DateTime.Now);
showed = true;
}
else if(check_online ==false && !nshowd)
{
Console.WriteLine("OFFline !!" + DateTime.Now);
nshowd = true;
}
}
答案 0 :(得分:2)
为什么showed
和nshowed
有不同的变量?你不想要一个is_online
变量然后证明与check_online
不同吗?
bool is_online = false;
for(;;)
{
bool check_online = check_online();
if (check_online != is_online)
{
// Online state has changed. Store the new state and log out
is_online = check_online;
if (is_online)
{
Console.WriteLine("Online !!" +DateTime.Now);
}
else
{
Console.WriteLine("Offline !!" +DateTime.Now);
}
}
}
答案 1 :(得分:1)
由于showed
和nshowd
是相互排斥的,所以维持它们都没有意义 - 这是布尔变量的全部要点:
userShown = false
while true:
userOnline = check_online()
if userOnline && !userShown:
output "User is online"
userShown = true
else:
if !userOnline && userShown:
output "User is offline"
userShown = false
sleep a bit
或者,您可以保持最后一个状态,只有在更改时才会显示:
isOnline = check_online()
wasOnline = !isOnline
while true:
if isOnline != wasOnline:
output "User is ", (isOnline) ? "online" : "offline"
wasOnline = isOnline
sleep a bit
isOnline = check_online()
这种特殊的方法可以保证输出初始消息,而无需用户的状态。
答案 2 :(得分:0)
你可以做一个循环,每次迭代等待10分钟吗?
bool toggle = false;
bool exitloop = false;
int checkinterval = 600; // time in seconds between check
while(!exitloop)
{
bool is_online = check_online();
if (is_online)
{
if (!toggle)
{
Console.WriteLine("Online!" + DateTime.Now.ToString();
toggle = true;
}
}
else
{
if (toggle)
{
Console.WriteLine("Offline!" + DateTime.Now.ToString());
toggle = false;
}
}
Thread.Sleep(checkinterval * 1000);
// it would be a good idea to allow a mechanism
// to exit from the infinite loop.
if (check_if_we_should_exit_loop())
{
exitloop = true;
}
}
答案 3 :(得分:0)
bool status = false;
bool statusChange = false;
while (true)
{
if (IsOnline())
{
if (status == false && statusChange == false)
statusChange = status = true;
else if (status == false && statusChange == true)
status = true;
else if (status == true && statusChange == false) ;
else if (status == true && statusChange == true)
statusChange = false;
}
else
{
if (status == false && statusChange == false) ;
else if (status == false && statusChange == true)
status = statusChange = false;
else if (status == true && statusChange == false)
{
status = false;
statusChange = true;
}
else if (status == true && statusChange == true)
statusChange = false;
}
if (statusChange)
{
UpdateStaus(status);
statusChange= false;
}
}