How to do for when click on the button perform action every 1 second

Asked

Viewed 727 times

0

I’m using Cefsharp and I wanted when clicked on the button runs the javascript every 1 second and in the background too, and only stop if you hit the off button. I tried for the backgroundworker but I couldn’t, I’m kind of layy in this part:

When you click the button runs the background worker:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    bool rodando = true;

    chromeBrowser.ExecuteScriptAsync("$(document).ready(function(){if($('#signup_button').is(':visible')){alert('Você precisa estar logado para utilizar o script')}})");

    try
    {
        Thread t = new Thread(() => 
        {
            while (rodando)
            {
                Thread.Sleep(1000);
                Script();
            }
        });

        t.Start();
    }
    catch
    {

    }
}

Shutdown:

private void btnscriptshutdown_Click(object sender, EventArgs e)
{
    if (worker.WorkerSupportsCancellation)
        worker.CancelAsync();
}

Only it’s not looping, it only runs once, as I can always run?

  • Still having trouble with that code?

  • Yeah just what I’m doing by the button now, without the background worker

  • You could try through a Timer..

  • How would you look to run until you hit a stop button?

  • I’ll put the code, give me a break.

1 answer

0


Instead of using a BackgroundWorker, you can use a Timer, library System.Timers.Timer.

Your code can be done as follows:

System.Timers.Timer _timer;

public Form1()
{
    InitializeComponent();

    // Botão para iniciar a thread
    btnStart.Click += Start_Click;

    // Botão para encerrar a thread
    btnStop.Click += Stop_Click;
}

private void Start_Click(object sender, EventArgs e)
{
    // Cria e inicia o timer para ser disparado a cada 1 segundo = (1000 ms)
    if (_timer == null)
    {
        chromeBrowser.ExecuteScriptAsync("$(document).ready(function(){if($('#signup_button').is(':visible')){alert('Você precisa estar logado para utilizar o script')}})");

        _timer = new System.Timers.Timer();
        _timer.Interval = 1000;
        _timer.Elapsed += Timer_Elapsed;
        _timer.Start();
    }
    else
    {
        MessageBox.Show("Já existe uma tarefa em andamento!");
    }
}

private void Stop_Click(object sender, EventArgs e)
{
    // Encerra o timer, se estiver ativo
    if (_timer != null && _timer.Enabled)
    {
        _timer.Stop();
        _timer.Enabled = false;
        _timer = null;
    }
}

// Código executado a cada 1 segundo
private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    Script();
}

In this example, the Form has two buttons: the btnStart that begins the thread and the btnStop, that stops the thread.

The method Timer_Elapsed is responsible for running your code every 1 second.

Important

As now your code is running in a thread separate from the main thread, in case you need to update any information on the screen, such as the text of Label, you must execute the respective code in the thread main, using Invoke.

Example

lblSeconds.Invoke(new Action(() =>
{
    lblSeconds.Text = "Label atualizado a partir de outra thread.";
}));
  • One question, how can I do if type Cefsharp executes a javascript then this javascript code looks like this: Alert('test'); how do I stop the timer? Why it keeps popping Alert every 1 second and there’s no way to click the STOP button

  • You can create a logic to start the timer only if the user has logged in.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.