Вот мой код:
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
@Override
public void run() {
}
});
}
} catch (InterruptedException e) {
}
}
};
thread.start();
Thread называется Thread, и я хочу отображать время в TextView, называемом TextView. В Thread есть некоторая ошибка, потому что, хотя время отображается в TextView, оно не обновляется каждую секунду. Спасибо
2 ответа
Используйте Runnable И < a href = «https://developer.android.com/reference/android/os/Handler.html» rel = «nofollow noreferrer»> Handler
Runnable runnable = new Runnable() {
@Override
public void run() {
Date time = Calendar.getInstance().getTime();
textView.setText(DateFormat.format("hh:mm", time));
handler.postDelayed(this, 1000);
}
};
Handler handler = new Handler();
handler.post(runnable);
2
Ali Faris
10 Авг 2017 в 14:36
Как уже говорилось, вы должны использовать Handler с Runnable, вот пример вашего кода:
final Handler handler = new Handler();
final Runnable task = new Runnable() {
@Override
public void run() {
//Your code
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(task, 1000);
Дополнительную информацию об обработчиках см. в документе.
2
Matias Olocco
10 Авг 2017 в 23:24
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 |
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using Microsoft.Win32; using System.Security.Principal; namespace Updater { public partial class Form1 : Form { public Form1() { InitializeComponent(); t.Tick += timer1_Tick; t2.Tick += timer2_Tick; this.Text = "Автоматический корректировщик "; // + FormUpdater.my_version; label3.Text = FormUpdater.my_version; } private void выходToolStripMenuItem_Click(object sender, EventArgs e) { // Close(); } private void оПрограммеToolStripMenuItem_Click(object sender, EventArgs e) { AboutBox1 a = new AboutBox1(); a.Show(); } private void button1_Click(object sender, EventArgs e) // 1 кнопка активация в ВК { if (timer1.Enabled) { System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.FileName = "open.exe"; p.Start(); button1.Text = "Открыть доступ в ВК r продолжит таймер"; timer1.Enabled = false; } else { System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.FileName = "close.exe"; p.Start(); button1.Text = "Приостановить таймер"; timer1.Enabled = true; } //MessageBox.Show("Критическая ошибка приложения n n Данная функция не работает в этой версии программы n Версия программы " + FormUpdater.my_version, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } private void настройкиToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show("Окошко №1 n n n Тестовая запись r Окно настроек ещё не готово", "Настройки...", MessageBoxButtons.OK, MessageBoxIcon.Question); } int i; int ti; private void button3_Click(object sender, EventArgs e) // 3 кнопка "Тестовая" { System.Diagnostics.Process z = new System.Diagnostics.Process(); z.StartInfo.FileName = @"open.exe"; z.Start(); RegistryKey readKey = Registry.LocalMachine.OpenSubKey("SYSTEM\CurrentControlSet\Services\Tcpip\Parameters"); string put = (string)readKey.GetValue("DataBasePath"); //Получаем путь до etc string put1 = put + "/hosts"; //Получаем путь до hosts // if(File.Exists("c:/windows/system32/drivers/etc/hosts")) это альтернативный способ проверки файла хостс if (File.Exists(put + "/hosts")) { /* string path = @"\localhostupdatehosts"; string path2 = @"c:"; string path3 = put; File.Copy(path, path2, true); File.Copy(path, path3, true); не работает данная хуйня обходим путём командной строки */ // string command = "xcopy "; // System.Diagnostics.Process.Start("cmd.exe", "/C " + command); //System.Diagnostics.Process.Start("cmd.exe", "/C " + "xcopy admin\update\close\hosts u0022%windir%\system32\drivers\etc\u0022 /H /E /G /Q /R /Y"); button3.Enabled = false; // делаем кнопку неактивной i = 3600; // время на открытие контакта label6.Text = i.ToString(); // отображение времени в поле "неизвестно" timer1.Interval = 1000; timer1.Enabled = true; // делаем таймер активным timer1.Start(); // запускаем таймер button3.Text = "Доступ в ВК активен на 1 час"; } else { MessageBox.Show("Критическая ошибка. r Срочно позовите системного администратора! n У Вас ВИРУС!!!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void timer1_Tick(object sender, EventArgs e) { i -= 1; string mm; string ss; string hh = (i / 3600).ToString(); if ((i % 3600) / 60 > 9) { mm = ((i % 3600) / 60).ToString(); } else { mm = "0" + ((i % 3600) / 60).ToString(); } if ((i % 3600) % 60 > 9) { ss = ((i % 3600) % 60).ToString(); } else { ss = "0" + ((i % 3600) % 60).ToString(); } label6.Text = hh + ":" + mm + ":" + ss; if (i < 0) timer1.Stop(); if (i < 0) MessageBox.Show("Ваше время доступа истекло n Пожалуйста сверните программу n n n Новый доступ будет доступен через 12 часов", "Завершение работы", MessageBoxButtons.OK, MessageBoxIcon.Stop); System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.FileName = @"close.exe"; p.Start(); } private void trackBar1_Scroll(object sender, EventArgs e) { Form1.ActiveForm.Opacity = trackBar1.Value / (double)trackBar1.Maximum; } private void Form1_Load(object sender, EventArgs e) { t2.Start(); ti = 28800; // время До конца рабочего дня label10.Text = i.ToString(); // отображение времени в поле "неизвестно" timer2.Interval = 1000; timer2.Enabled = true; // делаем таймер активным timer2.Start(); // запускаем таймер this.ControlBox = false; // При загрузке окна, Кнопка Закрыть исчезает System.Diagnostics.Process p = new System.Diagnostics.Process(); // Запускается командная строка с параметром Shutdown на 12 часов. Компьютер который не выключен перезагрузится. p.StartInfo.FileName = "cmd.exe"; p.StartInfo.Arguments = "/c shutdown -r -t 43200"; p.Start(); } private void button2_Click(object sender, EventArgs e) // Вторая кнопка спрятать программу { this.WindowState = FormWindowState.Minimized; this.ShowInTaskbar = false; } private void notifyIcon1_MouseDoubleClick_1(object sender, MouseEventArgs e) { this.WindowState = FormWindowState.Normal; this.ShowInTaskbar = true; } private void timer2_Tick(object sender, EventArgs e) { ti -= 1; string mm; string ss; string hh = (ti / 3600).ToString(); if ((ti % 3600) / 60 > 9) { mm = ((ti % 3600) / 60).ToString(); } else { mm = "0" + ((ti % 3600) / 60).ToString(); } if ((ti % 3600) % 60 > 9) { ss = ((ti % 3600) % 60).ToString(); } else { ss = "0" + ((ti % 3600) % 60).ToString(); } label10.Text = hh + ":" + mm + ":" + ss; if (ti < 0) timer2.Stop(); if (ti < 0) MessageBox.Show("Рабочий день закончен n Сходите отдохните, Вы весь день трудились в поте лица n Желаем Вам всего наилучшего. n Увидимся завтра. Покааа))", "Конец рабочего дня", MessageBoxButtons.OK, MessageBoxIcon.Stop); } private void notifyIcon1_MouseClick(object sender, MouseEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Right) { contextMenuStrip1.Show(Cursor.Position); } } private void toolStripMenuItem2_MouseClick(object sender, MouseEventArgs e) { MessageBox.Show("Working it's n n n n n n Программа работает корректно, доработки ведутся r Версия программульки " + FormUpdater.my_version, "работаетсуканах.."); } private void Form1_FormClosed(object sender, System.Windows.Forms.FormClosedEventArgs e) { this.WindowState = FormWindowState.Minimized; this.ShowInTaskbar = false; } private void Form1_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e) { this.WindowState = FormWindowState.Minimized; this.ShowInTaskbar = false; } } } |
Прошу помощи господа.
В моём говнокоде не могу найти ошибку.
Сделал запуск программы по нажатию на button
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "open.exe";
p.Start();
Но вот беда. Почему то мне каждую секунду открывает программу.
Полный код
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.Win32;
using System.Security.Principal;
namespace Updater
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
t.Tick += timer1_Tick;
t2.Tick += timer2_Tick;
this.Text = "Автоматический корректировщик "; // + FormUpdater.my_version;
label3.Text = FormUpdater.my_version;
}
private void выходToolStripMenuItem_Click(object sender, EventArgs e)
{
// Close();
}
private void оПрограммеToolStripMenuItem_Click(object sender, EventArgs e)
{
AboutBox1 a = new AboutBox1();
a.Show();
}
private void button1_Click(object sender, EventArgs e) // 1 кнопка активация в ВК
{
if (timer1.Enabled)
{
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "open.exe";
p.Start();
button1.Text = "Открыть доступ в ВК r продолжит таймер";
timer1.Enabled = false;
}
else
{
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "close.exe";
p.Start();
button1.Text = "Приостановить таймер";
timer1.Enabled = true;
}
//MessageBox.Show("Критическая ошибка приложения n n Данная функция не работает в этой версии программы n Версия программы " + FormUpdater.my_version, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void настройкиToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Окошко №1 n n n Тестовая запись r Окно настроек ещё не готово", "Настройки...", MessageBoxButtons.OK, MessageBoxIcon.Question);
}
int i;
int ti;
private void button3_Click(object sender, EventArgs e) // 3 кнопка "Тестовая"
{
System.Diagnostics.Process z = new System.Diagnostics.Process();
z.StartInfo.FileName = @"open.exe";
z.Start();
RegistryKey readKey = Registry.LocalMachine.OpenSubKey("SYSTEM\CurrentControlSet\Services\Tcpip\Parameters");
string put = (string)readKey.GetValue("DataBasePath"); //Получаем путь до etc
string put1 = put + "/hosts"; //Получаем путь до hosts
// if(File.Exists("c:/windows/system32/drivers/etc/hosts")) это альтернативный способ проверки файла хостс
if (File.Exists(put + "/hosts"))
{
/* string path = @"\localhostupdatehosts";
string path2 = @"c:";
string path3 = put;
File.Copy(path, path2, true);
File.Copy(path, path3, true);
не работает данная хуйня
обходим путём командной строки
*/
// string command = "xcopy ";
// System.Diagnostics.Process.Start("cmd.exe", "/C " + command);
//System.Diagnostics.Process.Start("cmd.exe", "/C " + "xcopy admin\update\close\hosts u0022%windir%\system32\drivers\etc\u0022 /H /E /G /Q /R /Y");
button3.Enabled = false; // делаем кнопку неактивной
i = 3600; // время на открытие контакта
label6.Text = i.ToString(); // отображение времени в поле "неизвестно"
timer1.Interval = 1000;
timer1.Enabled = true; // делаем таймер активным
timer1.Start(); // запускаем таймер
button3.Text = "Доступ в ВК активен на 1 час";
}
else
{
MessageBox.Show("Критическая ошибка. r Срочно позовите системного администратора! n У Вас ВИРУС!!!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
i -= 1;
string mm;
string ss;
string hh = (i / 3600).ToString();
if ((i % 3600) / 60 > 9)
{
mm = ((i % 3600) / 60).ToString();
}
else
{
mm = "0" + ((i % 3600) / 60).ToString();
}
if ((i % 3600) % 60 > 9)
{
ss = ((i % 3600) % 60).ToString();
}
else
{
ss = "0" + ((i % 3600) % 60).ToString();
}
label6.Text = hh + ":" + mm + ":" + ss;
if (i < 0)
timer1.Stop();
if (i < 0)
MessageBox.Show("Ваше время доступа истекло n Пожалуйста сверните программу n n n Новый доступ будет доступен через 12 часов", "Завершение работы", MessageBoxButtons.OK, MessageBoxIcon.Stop);
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = @"close.exe";
p.Start();
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
Form1.ActiveForm.Opacity = trackBar1.Value / (double)trackBar1.Maximum;
}
private void Form1_Load(object sender, EventArgs e)
{
t2.Start();
ti = 28800; // время До конца рабочего дня
label10.Text = i.ToString(); // отображение времени в поле "неизвестно"
timer2.Interval = 1000;
timer2.Enabled = true; // делаем таймер активным
timer2.Start(); // запускаем таймер
this.ControlBox = false; // При загрузке окна, Кнопка Закрыть исчезает
System.Diagnostics.Process p = new System.Diagnostics.Process(); // Запускается командная строка с параметром Shutdown на 12 часов. Компьютер который не выключен перезагрузится.
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c shutdown -r -t 43200";
p.Start();
}
private void button2_Click(object sender, EventArgs e) // Вторая кнопка спрятать программу
{
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;
}
private void notifyIcon1_MouseDoubleClick_1(object sender, MouseEventArgs e)
{
this.WindowState = FormWindowState.Normal;
this.ShowInTaskbar = true;
}
private void timer2_Tick(object sender, EventArgs e)
{
ti -= 1;
string mm;
string ss;
string hh = (ti / 3600).ToString();
if ((ti % 3600) / 60 > 9)
{
mm = ((ti % 3600) / 60).ToString();
}
else
{
mm = "0" + ((ti % 3600) / 60).ToString();
}
if ((ti % 3600) % 60 > 9)
{
ss = ((ti % 3600) % 60).ToString();
}
else
{
ss = "0" + ((ti % 3600) % 60).ToString();
}
label10.Text = hh + ":" + mm + ":" + ss;
if (ti < 0)
timer2.Stop();
if (ti < 0)
MessageBox.Show("Рабочий день закончен n Сходите отдохните, Вы весь день трудились в поте лица n Желаем Вам всего наилучшего. n Увидимся завтра. Покааа))", "Конец рабочего дня", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
contextMenuStrip1.Show(Cursor.Position);
}
}
private void toolStripMenuItem2_MouseClick(object sender, MouseEventArgs e)
{
MessageBox.Show("Working it's n n n n n n Программа работает корректно, доработки ведутся r Версия программульки " + FormUpdater.my_version, "работаетсуканах..");
}
private void Form1_FormClosed(object sender, System.Windows.Forms.FormClosedEventArgs e)
{
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;
}
private void Form1_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
{
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;
}
}
}
Я новичок в C# немогли бы вы мне помочь исправить код. Что бы действие повторялось каждую секунду. Т.е вылезал message box каждую секунду.
void StartTimer()
{
int timeout = 0;
while (true)
{
timeout = (1 - DateTime.Now.Second) * 1 - DateTime.Now.Millisecond;
Thread.Sleep(timeout);
MessageBox.Show("Nen");
}
}
задан 13 мая 2019 в 8:08
![]()
2
//Rextester.Program.Main is the entry point for your code. Don't change it.
//Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Timers;
using System.Threading.Tasks;
namespace Rextester
{
public class Program
{
private static System.Timers.Timer aTimer;
public static void Main(string[] args)
{
SetTimer();
Console.ReadLine();
aTimer.Stop();
aTimer.Dispose();
}
private static void SetTimer()
{
// Таймер с интервалом в секунду
aTimer = new System.Timers.Timer(1000);
// Событие когда таймер идет
aTimer.Elapsed += OnTimedEvent;
aTimer.AutoReset = true;
aTimer.Enabled = true;
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
Console.WriteLine(e.SignalTime);
//TODO
}
}
}
проверить можете тут
ответ дан 13 мая 2019 в 8:26
6
What I want is to be able to run a function every second, irrelevant of how long the function takes (it should always be under a second). I’ve considered a number of options but not sure which is best.
If I just use the delay function it isn’t going to take into account the time the function takes to run.
If I time the function and then subtract that from a second and make up the rest in the delay it’s not going to take into account the time calculations.
I tried using threading.timer (I’m not sure about the ins and outs of how this works) but it did seem to be slower than the 1s.
Here’s the code I tried for testing threading.timer:
def update(i):
sys.stdout.write(str(i)+'r')
sys.stdout.flush()
print i
i += 1
threading.Timer(1, update, [i]).start()
Is there a way to do this irrelevant of the length of the time the function takes?
asked May 30, 2012 at 9:07
3
This will do it, and its accuracy won’t drift with time.
import time
start_time = time.time()
interval = 1
for i in range(20):
time.sleep(start_time + i*interval - time.time())
f()
3
The approach using a threading.Timer (see code below) should in fact not be used, as a new thread is launched at every interval and this loop can never be stopped cleanly.
# as seen here: https://stackoverflow.com/a/3393759/1025391
def update(i):
threading.Timer(1, update, [i+1]).start()
# business logic here
If you want a background loop it is better to launch a new thread that runs a loop as described in the other answer. Which is able to receive a stop signal, s.t. you can join() the thread eventually.
This related answer seems to be a great starting point to implement this.
answered May 30, 2012 at 9:15
moooeeeepmoooeeeep
30.8k21 gold badges95 silver badges181 bronze badges
3
if f() always takes less than a second then to run it on a one second boundary (without a drift):
import time
while True:
time.sleep(1 - time.monotonic() % 1)
f()
The idea is from @Dave Rove’s answer to a similar question.
To understand how it works, consider an example:
time.monotonic()returns13.7andtime.sleep(0.3)is calledf()is called around (±some error)14seconds (sincetime.monotonic()epoch)f()is run and it takes0.1(< 1) secondstime.monotonic()returns around14.1seconds andtime.sleep(0.9)is called- Step 2. is repeated around
15seconds (sincetime.monotonic()epoch) f()is run and it takes0.3(< 1) seconds (note: the value is different from Step 2.)time.monotonic()returns around15.3andtime.sleep(0.7)is calledf()is called around16seconds and the loop is repeated.
At each step f() is called on a one second boundary (according to time.monotonic() timer). The errors do not accumulate. There is no drift.
See also: How to run a function periodically in python (using tkinter).
![]()
answered Feb 28, 2016 at 19:20
jfsjfs
390k188 gold badges962 silver badges1647 bronze badges
How about this: After each run, sleep for (1.0 - launch interval) seconds. You can change the terminate condition by changing while True:. Although if the your function takes more than 1 second to run, this will go wrong.
from time import time, sleep
while True:
startTime = time()
yourFunction()
endTime = time()-startTime
sleep(1.0-endTime)
answered May 30, 2012 at 9:29
lllluuukkelllluuukke
1,2942 gold badges12 silver badges17 bronze badges
Threading may be a good choice. The basic concept is as follows.
import threading
def looper():
# i as interval in seconds
threading.Timer(i, looper).start()
# put your action here
foo()
#to start
looper()
answered Jun 28, 2014 at 15:14
ZnatzZnatz
1,5402 gold badges18 silver badges30 bronze badges
I would like to recommend the following code. You can replace the True with any condition if you want.
while True:
time.sleep(1) #sleep for 1 second
func() #function you want to trigger
Tell me if it works.
answered Mar 31, 2020 at 6:53
GrasshopperGrasshopper
3432 silver badges13 bronze badges