Search Results

Search found 46009 results on 1841 pages for 'first timer'.

Page 5/1841 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Java Timer not working

    - by Jacob
    I have an Image named worldImageToUse and I have a Timer that is supposed to toggle worldImageToUse between two images every 1 second. But it does not seem to work. Help Please? public void startWorldImageFlash() { worldImageFlashTimer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { if(worldImageToUse == worldImage) setWorldImageBW(); if(worldImageToUse == worldImageBW) setWorldImageColor(); } }; worldImageFlashTimer.scheduleAtFixedRate(task, 0, 1000); } public void stopWorldImageFlash() { worldImageFlashTimer.cancel(); setWorldImageColor(); }

    Read the article

  • Keeping socket open to send files on timer calls?

    - by user3704768
    I'm writing a program that requires an image to be fetched from a remote server every 10 milliseconds or so, as that's how often the image is updated. My current method calls a timer to grab the image, but it encounters Socket Closed errors all the time, and sometimes does not work at all. How can I fix my methods to keep the socket open the whole time, so no reconnecting is needed? Here is the full class: import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import javax.swing.Timer; public class Connection { public static void createServer() throws IOException { Capture.getScreen(); ServerSocket socket = null; try { socket = new ServerSocket(12345, 0, InetAddress.getByName("127.0.0.1")); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Server started on " + socket.getInetAddress().getHostAddress() + ":" + socket.getLocalPort() + ",\nWaiting for client to connect."); final Socket clientConnection = socket.accept(); System.out.println("Client accepted from " + clientConnection.getInetAddress().getHostAddress() + ", sending file"); ActionListener taskPerformer = new ActionListener() { public void actionPerformed(ActionEvent evt) { System.out.println("Sending File"); try { pipeStreams(new FileInputStream(new File( "captures/sCap.png")), clientConnection.getOutputStream(), 1024); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }; System.out.println("closing out connection"); try { clientConnection.close(); } catch (IOException e) { e.printStackTrace(); } try { socket.close(); } catch (IOException e) { e.printStackTrace(); } Timer timer = new Timer(10, taskPerformer); timer.setRepeats(true); timer.start(); } public static void createClient() throws IOException { System.out.println("Connecting to server."); final Socket socket = new Socket(); try { socket.connect(new InetSocketAddress(InetAddress .getByName("127.0.0.1"), 12345)); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { } ActionListener taskPerformer = new ActionListener() { public void actionPerformed(ActionEvent evt) { System.out.println("Success, retreiving file."); try { pipeStreams(socket.getInputStream(), new FileOutputStream( new File("captures/rCap.png")), 1024); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { } } }; System.out.println("Closing connection"); try { socket.close(); } catch (IOException e) { e.printStackTrace(); } Timer timer = new Timer(10, taskPerformer); timer.setRepeats(true); timer.start(); } public static void pipeStreams(java.io.InputStream source, java.io.OutputStream destination, int bufferSize) throws IOException { byte[] buffer = new byte[bufferSize]; int read = 0; while ((read = source.read(buffer)) != -1) { destination.write(buffer, 0, read); } destination.flush(); destination.close(); source.close(); } }

    Read the article

  • System.Threading.Timer Doesn't Trigger my TimerCallBack Delegate

    - by Tom Kong
    Hi, I am writing my first Windows Service using C# and I am having some trouble with my Timer class. When the service is started, it runs as expected but the code will not execute again (I want it to run every minute) Please take a quick look at the attached source and let me know if you see any obvious mistakes! TIA using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading; using System.IO; namespace CXO001 { public partial class Service1 : ServiceBase { public Service1() { InitializeComponent(); } /* * Aim: To calculate and update the Occupancy values for the different Sites * * Method: Retrieve data every minute, updating a public value which can be polled */ protected override void OnStart(string[] args) { Daemon(); } public void Daemon() { TimerCallback tcb = new TimerCallback(On_Tick); TimeSpan duetime = new TimeSpan(0, 0, 1); TimeSpan interval = new TimeSpan(0, 1, 0); Timer querytimer = new Timer(tcb, null, duetime, interval); } protected override void OnStop() { } static int[] floorplanids = new int[] { 115, 114, 107, 108 }; public static List<Record> Records = new List<Record>(); static bool firstrun = true; public static void On_Tick(object timercallback) { //Update occupancy data for the last minute //Save a copy of the public values to HDD with a timestamp string starttime; if (Records.Count > 0) { starttime = Records.Last().TS; firstrun = false; } else { starttime = DateTime.Today.AddHours(7).ToString(); firstrun = true; } DateTime endtime = DateTime.Now; GetData(starttime, endtime); } public static void GetData(string starttime, DateTime endtime) { string connstr = "Data Source = 192.168.1.123; Initial Catalog = Brickstream_OPS; User Id = Brickstream; Password = bstas;"; DataSet resultds = new DataSet(); //Get the occupancy for each Zone foreach (int zone in floorplanids) { SQL s = new SQL(); string querystr = "SELECT SUM(DIRECTIONAL_METRIC.NUM_TO_ENTER - DIRECTIONAL_METRIC.NUM_TO_EXIT) AS 'Occupancy' FROM REPORT_OBJECT INNER JOIN REPORT_OBJ_METRIC ON REPORT_OBJECT.REPORT_OBJ_ID = REPORT_OBJ_METRIC.REPORT_OBJECT_ID INNER JOIN DIRECTIONAL_METRIC ON REPORT_OBJ_METRIC.REP_OBJ_METRIC_ID = DIRECTIONAL_METRIC.REP_OBJ_METRIC_ID WHERE (REPORT_OBJ_METRIC.M_START_TIME BETWEEN '" + starttime + "' AND '" + endtime.ToString() + "') AND (REPORT_OBJECT.FLOORPLAN_ID = '" + zone + "');"; resultds = s.Go(querystr, connstr, zone.ToString(), resultds); } List<Record> result = new List<Record>(); int c = 0; foreach (DataTable dt in resultds.Tables) { Record r = new Record(); r.TS = DateTime.Now.ToString(); r.Zone = dt.TableName; if (!firstrun) { r.Occupancy = (dt.Rows[0].Field<int>("Occupancy")) + (Records[c].Occupancy); } else { r.Occupancy = dt.Rows[0].Field<int>("Occupancy"); } result.Add(r); c++; } Records = result; MrWriter(); } public static void MrWriter() { StringBuilder output = new StringBuilder("Time,Zone,Occupancy\n"); foreach (Record r in Records) { output.Append(r.TS); output.Append(","); output.Append(r.Zone); output.Append(","); output.Append(r.Occupancy.ToString()); output.Append("\n"); } output.Append(firstrun.ToString()); output.Append(DateTime.Now.ToFileTime()); string filePath = @"C:\temp\CXO.csv"; File.WriteAllText(filePath, output.ToString()); } } }

    Read the article

  • EJB3 + JEE6: What is a persistent Timer?

    - by Hank
    I'm just about to use the new EJB3 TimerService (as part of Java EE 6), and as usual, I'm impressed by the brevity of JavaDoc :) Do you know what is the effect of the persistent property of the TimerConfig object? JavaDoc TimerConfig says: The persistent property determines whether the corresponding timer has a lifetime that spans the JVM in which it was created. It is optional and defaults to true.

    Read the article

  • How to capture screen with timer using C#?

    - by ankush
    This is a Windows application using C#. I want to capture a screen shot with a timer. The timer is set to a 5000 ms interval. As the timer is started, the desktop screen should be captured with the source window caption. try { System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer(); timer.Tick += new EventHandler(timer2_Tick); timer.Interval = (100) * (50); timer.Enabled = true; timer.Start(); ScreenShots sc = new ScreenShots(); sc.pictureBox1.Image = system_serveillance.CaptureScreen.GetDesktopImage(); while(sc.pictureBox1.Image != null) { sc.pictureBox1.Image.Save("s"+".jpg", System.Drawing.Imaging.ImageFormat.Jpeg); sc.pictureBox1.Image = null; } This code is not working properly. How can I make it work?

    Read the article

  • Penny auction concept and how the timer works

    - by madi
    I am creating a penny auction site using PHP yii framework. The main consideration of the system is to update the database records of all active auctions (max 15 auctions) with the current ticker timer. I am seeking for advice on how i should design the system where every auction item will have a its own countdown timer stored in the database and when someone bids the auction item, the counter resets to 2 min. Every users who are connected to the system should see the same countdown timer for that particular auction. I am little confused on how i should design the system. Will there be a performance issue when there are frequent updates to the database (Mysql) where 15 active auctions are updated every seconds, the countdown timer decreases by a second in the database table for the particular auction. Schema Sample for auction_lots: Auction_id,startdatetime,counter_timer,status I am seeking for advice on how I should design this. Please help. Thank you!

    Read the article

  • Adjusting the rate of movement of different objects on the same timer

    - by theUg
    I have a series of objects moving along the straight lines. I want to implement slight changes of velocity of each of the object. Constraint is existing model of animation. I am new to this, and not sure if it is the best way to accommodate varying speeds, but what do I know? It is a Java application that repaints the panel every time the timer expires. Timer is set via swing.Timer object that is set by timer delay constant. Every time the game is stepped objects’ coordinates advanced by an increment constant. Most of the objects are of the same class. Is there fairly easy way to refactor existing system to allow changing velocity for an individual object? Is there some obvious common solution I am not aware about? Idea I am having right now is to set timer delay fairly small, and only move objects every so many cycles of animation so that the apparent speed can be adjusted by varying how often they get moved. But that seems fairly involved, and I do not think it is the most elegant solution in terms of performance what with repainting the whole frame every 3-5 milliseconds. Can it be done by advancing the objects so many (varying) times during the certain interval (let’s say 35ms for something like 28fps), and use repaint() method to redraw just individual object? Do I need to mess with pausing animation for smoothness at higher redraw rates? Is it common practise to check for collision at larger step interval, but draw animation a lot more frequently?

    Read the article

  • Dispatcher Timer Problem

    - by will
    I am trying to make a game in silverlight that also has widgets in it. To do this I am using a dispatcher timer running a game loop that updates graphics etc. In this I have a variable that has to be accessed by both by the constantly running game loop and UI event code. At first look it seemed that the gameloop had its own local copy of currentUnit (the variable), despite the variable being declared globally. I am trying to update currentUnit with an event by the widget part of the app, but the timer's version of the variable is not being updated. What can I do get the currentUnit in the gameloop loop to be updated whenever I update currentUnit via a click event? Here is the code for setting currentUnit as part of a click event DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Unit)); currentUnit = serializer.ReadObject(e.Result) as Unit; txtName.Text = currentUnit.name; Canvas.SetLeft(txtName, 100 - (int)Math.Ceiling(txtName.ActualWidth) / 2); txtX.Text = "" + currentUnit.x; txtY.Text = "" + currentUnit.y; txtX.Text = "" + currentUnit.owner; txtY.Text = "" + currentUnit.moved; txtName.Text = "" + currentUnit.GetHashCode(); And here is a snippet from the gameLoop loop //deal with phase changes and showing stuff if (txtPhase.Text == "Move" && movementPanel.Visibility == Visibility.Collapsed) { if (currentUnit != null) { if (currentUnit.owner) { if (currentUnit.moved) { txtMoved.Text = "This Unit has Already Moved!"; movementPanel.Visibility = Visibility.Collapsed; } else { txtMoved.Text = "" + currentUnit.GetHashCode(); movementPanel.Visibility = Visibility.Visible; } } else { txtMoved.Text = "bam"; movementPanel.Visibility = Visibility.Collapsed; } } else { txtMoved.Text = "slam"; movementPanel.Visibility = Visibility.Collapsed; } //loadUnitList(); } Here is the code for my unit class. using System; public class Unit { public int id { get; set; } public string name { get; set; } public string image { get; set; } public int x { get; set; } public int y { get; set; } public bool owner { get; set; } public int rotation { get; set; } public double movement { get; set; } public string type { get; set; } public bool moved { get; set; } public bool fired { get; set; } } Overall, any simple types, like a double is being 'updated' correctly, yet a complex of my own type (Unit) seems to be holding a local copy. Please help, I've asked other places and no one has had an answer for me!

    Read the article

  • Timer or Thread?

    - by Pradeep Singh
    I have a method(say method1) that writes to database(sqlserver)and another method(say method2) that tries to access the same database after some time and updates the data row that was created by method1. The problem arises when method1 fails to access db due to the LAN being disconnected (this is not an exception this is a scenario that will definitely arise in my software, getting into details will make the question too complex) if method1 fails to access db method2 cannot work. What I want to do is to make method1 store values to local db instead of server if the LAN is disconnected and as soon as it enters value in local db the application should start trying to access the server after ever 10-15 seconds. What should I use timer or create a new thread?

    Read the article

  • Non-reentrant C# timer

    - by Oak
    I'm trying to invoke a method f() every t time, but if the previous invocation of f() has not finished yet, wait until it's finished. I've read a bit about the available timers (this is a useful link) but couldn't find any good way of doing what I want, save for manually writing it all. Any help about how to achieve this will be appreciated, though I fear I might not be able to find a simple solution using timers. To clarify, if x is one second, and f() runs the arbitrary durations I've written below, then: Step Operation Time taken 1 wait 1s 2 f() 0.6s 3 wait 0.4s (because f already took 0.6 seconds) 4 f() 10s 5 wait 0s (we're late) 6 f() 0.3s 7 wait 0.7s (we can disregard the debt from step 4) Notice that the nature of this timer is that f() will not need to be safe regarding re-entrance, and a thread pool of size 1 is enough here.

    Read the article

  • actionscript display timer

    - by Aaron
    ok so im using real basic code for a small game and ive got a timer set up on one room and cant get it to display in the endgame room please help? this is the code i used var gameStartTime:uint; var gameTime:uint; var gameTimeField:TextField; gameTimeField = new TextField(); gameTimeField.x = 900; gameTimeField.y = 50; addChild(gameTimeField); gameStartTime = getTimer(); gameTime = 0; addEventListener(Event.ENTER_FRAME,showTime); function showTime(event:Event) {gameTime = getTimer()-gameStartTime; gameTimeField.text = "Time: "+clockTime(gameTime); } function clockTime(ms:int) { var seconds:int = Math.floor(ms/100); var minutes:int = Math.floor(seconds/60); seconds -= minutes*60; var timeString:String = minutes+":"+String(seconds+100).substr(1,2); return timeString; }

    Read the article

  • Fast, cross-platform timer?

    - by dsimcha
    I'm looking to improve the D garbage collector by adding some heuristics to avoid garbage collection runs that are unlikely to result in significant freeing. One heuristic I'd like to add is that GC should not be run more than once per X amount of time (maybe once per second or so). To do this I need a timer with the following properties: It must be able to grab the correct time with minimal overhead. Calling core.stdc.time takes an amount of time roughly equivalent to a small memory allocation, so it's not a good option. Ideally, should be cross-platform (both OS and CPU), for maintenance simplicity. Super high resolution isn't terribly important. If the times are accurate to maybe 1/4 of a second, that's good enough. Must work in a multithreaded/multi-CPU context. The x86 rdtsc instruction won't work.

    Read the article

  • C# Timer counter in xx.xx.xx format

    - by Darkshadw
    I have a counter that counts up every 1 second and add 1 to an int. Question How can I format my string so the counter would look like this: 00:01:23 Instead of: 123 Things I've tried Things I've tried so far: for (int i = 0; i < 1; i++) { _Counter += 1; labelUpTime.Text = _Counter.ToString(); } My timer's interval is set to: 1000 (so it adds 1 every second). I did read something about string.Format(""), but I don't know if it is applicable. Thanks if you can guide me through this :D!

    Read the article

  • System.Timers.Timer leaking due to "direct delegate roots"

    - by alimbada
    Apologies for the rather verbose and long-winded post, but this problem's been perplexing me for a few weeks now so I'm posting as much information as I can in order to get this resolved quickly. We have a WPF UserControl which is being loaded by a 3rd party app. The 3rd party app is a presentation application which loads and unloads controls on a schedule defined by an XML file which is downloaded from a server. Our control, when it is loaded into the application makes a web request to a web service and uses the data from the response to display some information. We're using an MVVM architecture for the control. The entry point of the control is a method that is implementing an interface exposed by the main app and this is where the control's configuration is set up. This is also where I set the DataContext of our control to our MainViewModel. The MainViewModel has two other view models as properties and the main UserControl has two child controls. Depending on the data received from the web service, the main UserControl decides which child control to display, e.g. if there is a HTTP error or the data received is not valid, then display child control A, otherwise display child control B. As you'd expect, these two child controls bind two separate view models each of which is a property of MainViewModel. Now child control B (which is displayed when the data is valid) has a RefreshService property/field. RefreshService is an object that is responsible for updating the model in a number of ways and contains 4 System.Timers.Timers; a _modelRefreshTimer a _viewRefreshTimer a _pageSwitchTimer a _retryFeedRetrievalOnErrorTimer (this is only enabled when something goes wrong with retrieving data). I should mention at this point that there are two types of data; the first changes every minute, the second changes every few hours. The controls' configuration decides which type we are using/displaying. If data is of the first type then we update the model quite frequently (every 30 seconds) using the _modelRefreshTimer's events. If the data is of the second type then we update the model after a longer interval. However, the view still needs to be refreshed every 30 seconds as stale data needs to be removed from the view (hence the _viewRefreshTimer). The control also paginates the data so we can see more than we can fit on the display area. This works by breaking the data up into Lists and switching the CurrentPage (which is a List) property of the view model to the right List. This is done by handling the _pageSwitchTimer's Elapsed event. Now the problem My problem is that the control, when removed from the visual tree doesn't dispose of it's timers. This was first noticed when we started getting an unusually high number of requests on the web server end very soon after deploying this control and found that requests were being made at least once a second! We found that the timers were living on and not stopping hours after the control had been removed from view and that the more timers there were the more requests piled up at the web server. My first solution was to implement IDisposable for the RefreshService and do some clean up when the control's UnLoaded event was fired. Within the RefreshServices Dispose method I've set Enabled to false for all the timers, then used the Stop() method on all of them. I've then called Dispose() too and set them to null. None of this worked. After some reading around I found that event handlers may hold references to Timers and prevent them from being disposed and collected. After some more reading and researching I found that the best way around this was to use the Weak Event Pattern. Using this blog and this blog I've managed to work around the shortcomings in the Weak Event pattern. However, none of this solves the problem. Timers are still not being disabled or stopped (let alone disposed) and web requests are continuing to build up. Mem Profiler tells me that "This type has N instances that are directly rooted by a delegate. This can indicate the delegate has not been properly removed" (where N is the number of instances). As far as I can tell though, all listeners of the Elapsed event for the timers are being removed during the cleanup so I can't understand why the timers continue to run. Thanks for reading. Eagerly awaiting your suggestions/comments/solutions (if you got this far :-p)

    Read the article

  • javascript countdown timer with cookies

    - by jwesonga
    I have a countdown timer that will show a target amount to be fundraised like USD1000000 and slowly count backwards to zero over a period of days. I got this snippet: $(function() { var cnt = 75000000; var count = setInterval(function() { if (cnt > 0) { $('#target').html("<span>KSHS</span><strong>" + cnt + " Target </strong>"); cnt--; } else { clearInterval(count); $('#target').html("<strong> Target Achieved! </strong>"); } }, 4000); }); The only problem is that everytime you refresh the page the counter starts again which essentially means it will never end. I'd like it that a when a user revisits/refreshes the page the counter persists and continues. I've read that javascript cookies can be used for this, just don't know how to implement them, any help?

    Read the article

  • javascript watching for variable change via a timer

    - by DA
    I have a slide show where every 10 seconds the next image loads. Once an image loads, it waits 10 seconds (setTimeout) and then calls a function which fades it out, then calls the function again to fade in the next image. It repeats indefinitely. This works. However, at times, I'm going to want to over-ride this "function1 call - pause - function2 call - function1 call" loop outside of this function (for instance, I may click on a slide # and want to jump directly to that slide and cancel the current pause). One solution seems to be to set up a variable, allow other events to change that variable and then in my original function chain, check for any changes before continuing the loop. I have this set up: var ping = 500; var pausetime = 10000; for(i=0; i<=pausetime; i=i+ping){ setTimeout(function(){ console.log(gocheckthevariable()); console.log(i); pseudoIf('the variable is true AND the timer is done then...do the next thing') },i) } The idea is that I'd like to pause for 10 seconds. During this pause, every half second I'll check to see if this should be stopped. The above will write out to the console the following every half second: true 10000 true 10000 true 10000 etc... But what I want/need is this: true 0 true 500 true 1000 etc... The basic problem is that the for loop executes before each of the set timeouts. While I can check the value of the variable every half second, I can't match that against the current loop index. I'm sure this is a common issue, but I'm at a loss what I should actually be searching for.

    Read the article

  • Need a Java based interruptible timer thread

    - by LambeauLeap
    I have a Main Program which is running a script on the target device(smart phone) and in a while loop waiting for stdout messages. However in this particular case, some of the heartbeat messages on the stdout could be spaced almost 45secs to a 1minute apart. something like: stream = device.runProgram(RESTORE_LOGS, new String[] {}); stream.flush(); String line = stream.readLine(); while (line.compareTo("") != 0) { reporter.commentOnJob(jobId, line); line = stream.readLine(); } So, I want to be a able to start a new interruptible thread after reading line from stdout with a required a sleep window. Upon being able to read a new line, I want to be able to interrupt/stop(having trouble killing the process), handle the newline of stdout text and restart a process. And it the event I am not able to read a line within the timer window(say 45secs) I want to a way to get out of my while loop either. I already tried the thread.run, thread.interrupt approach. But having trouble killing and starting a new thread. Is this the best way out or am I missing something obvious?

    Read the article

  • android game performance regarding timers

    - by iQue
    Im new to the game-dev world and I have a tendancy to over-simplify my code, and sometimes this costs me alot fo memory. Im using a custom TimerTask that looks like this: public class Task extends TimerTask { private MainGamePanel panel; public Task(MainGamePanel panel) { this.panel=panel; } /** * When the timer executes, this code is run. */ public void run() { panel.createEnemies(); } } this task calls this method from my view: public void createEnemies() { Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.female); if(enemyCounter < 24){ enemies.add(new Enemy(bmp, this)); } enemyCounter++; } Since I call this in the onCreate-method instead of in my views contructor (because My enemies need to get width and height of view). Im wondering if this will work when I have multiple levels in game (start a new intent). And if this kind of timer really is the best way to add a delay between the spawning-time of my enemies performance-wise. adding code for my timer if any1 came here cus they dont understand timers: private Timer timer1 = new Timer(); private long delay1 = 5*1000; // 5 sec delay public void surfaceCreated(SurfaceHolder holder) { timer1.schedule(new Task(this), 0, delay1); //I call my timer and add the delay thread.setRunning(true); thread.start(); }

    Read the article

  • Long Running Stored Proc - Report Progress Using BackgroundWorker & Timer

    - by daveywc
    While a long running stored proc (RMR_Seek) is executing (called via a Linq-To-SQL data context) I am trying to call another stored proc (RMR_GetLatestModelMessage) to check a table for the latest status message. The long running stored proc updates the table in question with status messages as it executes. I want to display the status message on a message panel to advise the user of the status of the execution of Proc_A. For various reasons it is not possible to determine how long RMR_Seek will take to execute so a progress bar with percentage increments is not feasible. I thought I'd found the way to do it by calling the long running stored proc from in a BackgroundWorker process DoWork event handler. This worked fine and allowed me to update my message panel with some dummy status messages that were NOT obtained via Proc_B while Proc_A was running. However now that I have tried to implement this fully by calling Proc_B to obtain the status messages I am running into problems that seem to be related to the mix of the backgroundworker and my System.Windows.Forms.Timer. An extract of the code I am using is below. I have tried many different ways around this but each one seems to present its own set of problems. The code below is problematic in the bw_DoWork event. The RMR_Seek stored proc gets called but does not execute properly - it also seems to be inconsistent as to whether _IsCompleted gets set to true. I'm sure there is a better way to achieve what I am trying to do. private bool _IsCompleted; private void RunRevenueSeek() { if (_SelectedModel == null) { MessageBox.Show("Please select a model from the list and try again.", "Model Generation", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { var bw = new BackgroundWorker(); bw.DoWork += new DoWorkEventHandler(bw_DoWork); ProgressPanelControl.Visible = true; _IsCompleted = false; MessageTimer.Start(); // Has an interval of 3000 bw.RunWorkerAsync(); ProgressLabelControl.Text = "Refreshing Data"; this.Update(); ...more code goes here } } private void bw_DoWork(object sender, DoWorkEventArgs e) { using (var dc = new RevMdlrDataClassesDataContext()) { dc.CommandTimeout = 300; dc.RMR_Seek(_SelectedModel.ModelSet_ID); _IsCompleted = true; } } private void MessageTimer_Tick(object sender, EventArgs e) { string message = ""; if (_IsCompleted) { MessageTimer.Stop(); } else { using (var dc = new RevMdlrDataClassesDataContext()) { dc.CommandTimeout = 300; dc.RMR_GetLatestModelMessage(_SelectedModel.ModelSet_ID, ref message); ProgressLabelControl.Text = message; this.Update(); } } }

    Read the article

  • How to save timers with connection to OrderId?

    - by Adrian Serafin
    Hi! I have a system where clients can make orders. After making order they have 60 minutes to pay fot it before it will be deleted. On the server side when order is made i create timer and set elapsed time to 60 minutes System.Timer.Timers timer = new System.Timers.Timer(1000*60*60); timer.AutoReset = false; timer.Elapsed += HandleElapsed; timer.Start(); Because I want to be able to dispose timer if client decides to pay and I want to be able to cancel order if he doesn't I keep two Dictionaries: Dictionary<int, Timer> _orderTimer; Dictionary<Timer, int> _timerOrder; Then when client pay's I can access Timer by orderId with O(1) thanks to _orderTimer dictionary and when time elapsed I can access order with O(1) thanks to _timerOrder dictionary. My question is: Is it good aproach? Assuming that max number of rows I have to keep in dictionary in one moment will be 50000? Maybe it would be better to derive from Timer class, add property called OrderId, keep it all in List and search for order/timer using linq? Or maybe you I should do this in different way?

    Read the article

  • How to change the way that timer schedules in TimerTask?

    - by Judking
    Here is the code snippet: Timer t = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { //change the timer rate of scheduleAtFixedRate here } }; //every 10 sec t.scheduleAtFixedRate(task, new Date(), 10000); Could anyone tell me how to change the rate of timer to t.scheduleAtFixedRate(task, new Date(), 30000) in method run from TimerTask instance? Thanks a lot!

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >