Search Results

Search found 1610 results on 65 pages for 'timer'.

Page 16/65 | < Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >

  • Multiple Timers with setTimeInterval

    - by visibleinvisibly
    I am facing a problem with setInterval being used in a loop. I have a function subscribeFeed( ) which takes an array of urls as input. It loops through the url array and subscribes each url to getFeedAutomatically() using a setInterval function. so if three URL's are there in the array, then 3 setInterval's will be called. The problem is 1)how to distinguish which setInterval is called for which URL. 2)it is causing Runtime exception in setInterval( i guess because of closure problem in javascript) //constructor function myfeed(){ this.feedArray = []; } myfeed.prototype.constructor= myfeed; myfeed.prototype.subscribeFeed =function(feedUrl){ var i=0; var url; var count = 0; var _this = this; var feedInfo = { url : [], status : "" }; var urlinfo = []; feedUrl = (feedUrl instanceof Array) ? feedUrl : [feedUrl]; //notifyInterval = (notifyInterval instanceof Array) ? notifyInterval: [notifyInterval]; for (i = 0; i < feedUrl.length; i++) { urlinfo[i] = { url:'', notifyInterval:5000,// Default Notify/Refresh interval for the feed isenable:true, // true allows the feed to be fetched from the URL timerID: null, //default ID is null called : false, position : 0, getFeedAutomatically : function(url){ _this.getFeedUpdate(url); }, }; urlinfo[i].url = feedUrl[i].URL; //overide the default notify interval if(feedUrl[i].NotifyInterval /*&& (feedUrl[i] !=undefined)*/){ urlinfo[i].notifyInterval = feedUrl[i].NotifyInterval; } // Trigger the Feed registered event with the info about URL and status feedInfo.url[i] = feedUrl[i].URL; //Set the interval to get the feed. urlinfo[i].timerID = setInterval(function(){ urlinfo[i].getFeedAutomatically(urlinfo[i].url); }, urlinfo[i].notifyInterval); this.feedArray.push(urlinfo[i]); } } // The getFeedUpate function will make an Ajax request and coninue myfeed.prototype.getFeedUpdate = function( ){ } I am posting the same on jsfiddle http://jsfiddle.net/visibleinvisibly/S37Rj/ Thanking you in advance

    Read the article

  • Android Stop Counter and Destroy Media Player

    - by dweebsonduty
    I am working on an app that beeps every second. When I hit the home button I want it to close the program and stop beeping. Right now it closes the program but continues to beep. What am I doing wrong? if ((keyCode == KeyEvent.KEYCODE_HOME)) { isdone = true; mp.release(); counter.cancel(); finish(); }

    Read the article

  • jQuery API counter++ pause on hover and then resume

    - by Rory
    I need to have this counter pause {stay on current div) while mouseover or hover and resume counter when mouseout. I have tried many ways but still new to jQuery API. <div id="slide_holder"> <div id="slide1" class="hidden"> <img src="images/crane2.jpg" class="fill"> </div> <div id="slide2" class="hidden"> <img src="images/extend_boom.png" class="fill"> </div> <div id="slide3" class="hidden"> <img src="images/Transformers-Bumblebee.jpg" class="fill"> </div> <script> $(function () { var counter = 0, divs = $('#slide1, #slide2, #slide3'); function showDiv () { divs.hide() // hide all divs .filter(function (index) { return index == counter % 3; }) // figure out correct div to show .fadeIn('slow'); // and show it counter++; }; // function to loop through divs and show correct div showDiv(); // show first div setInterval(function () { showDiv(); // show next div }, 3 * 1000); // do this every 10 seconds }); </script>

    Read the article

  • SQL Server Stored Procedure that return processed records number

    - by Ras
    I have a winform application that fires a Stored Procedure which elaborates several records (around 500k). In order to inform the user about how many record have been processed, I would need a SP which returns a value every n records. For example, every 1000 row processed (most are INSERT). Otherwise I would be able only to inform when ALL record are processed. Any hints how to solve this? I thought it could be useful to use a trigger or some scheduled task, but I cannot figure out how to implement it.

    Read the article

  • C++ obtaining milliseconds time on Linux -- clock() doesn't seem to work properly

    - by hasen j
    On Windows, clock() returns the time in milliseconds, but on this Linux box I'm working on, it rounds it to the nearest 1000 so the precision is only to the "second" level and not to the milliseconds level. I found a solution with Qt using the QTime class, instantiating an object and calling start() on it then calling elapsed() to get the number of milliseconds elapsed. I got kind of lucky because I'm working with Qt to begin with, but I'd like a solution that doesn't rely on third party libraries, Is there no standard way to do this? UPDATE Please don't recommend Boost .. If Boost and Qt can do it, surely it's not magic, there must be something standard that they're using!

    Read the article

  • C++: How do I pass a function(without knowing its parameters) to another function?

    - by Ninja
    Hi all. I'm trying to create a function that will store and repeat another function given as a parameter for a specific amount of time or repeats given. But when you want to pass a function as a parameter you have to know all of its parameters before hand. How would I do if I wanted to pass the function as one parameter, and the parameters as another? void AddTimer(float time, int repeats, void (*func), params); // I know params has no type and that (*func) is missing parameters but it is just to show you what I mean Thanks in advance

    Read the article

  • How do I make java wait for boolean to run funciton

    - by TWeeKeD
    I'm sure this is pretty simple but I can't figure out and it sucks I'm up on suck on (what should be) an easy step. ok. I have a method that runs one function that give a response. this method actually handles the uploading of the file so o it takes a second to give a response. I need this response in the following method. sendPicMsg needs to complete and then forward it's response to sendMessage. Please help. b1.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(!uploadMsgPic.equalsIgnoreCase("")){ Log.v("response","Pic in storage"); sendPicMsg(); sendMessage(); }else{ sendMessage(); } 1st Method public void sendPicMsg(){ Log.v("response", "sendPicMsg Loaded"); if(!uploadMsgPic.equalsIgnoreCase("")){ final SharedPreferences preferences = this.getActivity().getSharedPreferences("MyPreferences", getActivity().MODE_PRIVATE); AsyncHttpClient client3 = new AsyncHttpClient(); RequestParams params3 = new RequestParams(); File file = new File(uploadMsgPic); try { File f = new File(uploadMsgPic.replace(".", "1.")); f.createNewFile(); //Convert bitmap to byte array Bitmap bitmap = decodeFile(file,400); ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos); byte[] bitmapdata = bos.toByteArray(); //write the bytes in file FileOutputStream fos = new FileOutputStream(f); fos.write(bitmapdata); params3.put("file", f); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } params3.put("email", preferences.getString("loggedin_user", "")); params3.put("webversion", "1"); client3.post("http://peekatu.com/apiweb/msgPic_upload.php",params3, new AsyncHttpResponseHandler() { @Override public void onSuccess(String response) { Log.v("response", "Upload Complete"); refreshChat(); //responseString = response; Log.v("response","msgPic has been uploaded"+response); //parseChatMessages(response); response=picurl; uploadMsgPic = ""; if(picurl!=null){ Log.v("response","picurl is set"); } if(picurl==null){ Log.v("response", "picurl no ready"); }; } }); sendMessage(); } } 2nd Method public void sendMessage(){ final SharedPreferences preferences = this.getActivity().getSharedPreferences("MyPreferences", getActivity().MODE_PRIVATE); if(preferences.getString("Username", "").length()<=0){ editText1.setText(""); Toast.makeText(this.getActivity(), "Please Login to send messages.", 2); return; } AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = new RequestParams(); if(type.equalsIgnoreCase("3")){ params.put("toid",user); params.put("action", "sendprivate"); }else{ params.put("room", preferences.getString("selected_room", "Adult Lobby")); params.put("action", "insert"); } Log.v("response", "Sending message "+editText1.getText().toString()); params.put("message",editText1.getText().toString() ); params.put("media", picurl); params.put("email", preferences.getString("loggedin_user", "")); params.put("webversion", "1"); client.post("http://peekatu.com/apiweb/messagetest.php",params, new AsyncHttpResponseHandler() { @Override public void onSuccess(String response) { refreshChat(); //responseString = response; Log.v("response", response); //parseChatMessages(response); if(picurl!=null) Log.v("response", picurl); } }); editText1.setText(""); lv.setSelection(adapter.getCount() - 1); }

    Read the article

  • Windows Phone 7 : Dragging and flicking UI controls

    - by TechTwaddle
    Who would want to flick and drag UI controls!? There might not be many use cases but I think some concepts here are worthy of a post. So we will create a simple silverlight application for windows phone 7, containing a canvas element on which we’ll place a button control and an image and then, as the title says, drag and flick the controls. Here’s Mainpage.xaml, <Grid x:Name="LayoutRoot" Background="Transparent">   <Grid.RowDefinitions>     <RowDefinition Height="Auto"/>     <RowDefinition Height="*"/>   </Grid.RowDefinitions>     <!--TitlePanel contains the name of the application and page title-->   <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">     <TextBlock x:Name="ApplicationTitle" Text="KINETICS" Style="{StaticResource PhoneTextNormalStyle}"/>     <TextBlock x:Name="PageTitle" Text="drag and flick" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>   </StackPanel>     <!--ContentPanel - place additional content here-->   <Grid x:Name="ContentPanel" Grid.Row="1" >     <Canvas x:Name="MainCanvas" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">       <Canvas.Background>         <LinearGradientBrush StartPoint="0 0" EndPoint="0 1">           <GradientStop Offset="0" Color="Black"/>           <GradientStop Offset="1.5" Color="BlanchedAlmond"/>         </LinearGradientBrush>       </Canvas.Background>     </Canvas>   </Grid> </Grid> the second row in the main grid contains a canvas element, MainCanvas, with its horizontal and vertical alignment set to stretch so that it occupies the entire grid. The canvas background is a linear gradient brush starting with Black and ending with BlanchedAlmond. We’ll add the button and image control to this canvas at run time. Moving to Mainpage.xaml.cs the Mainpage class contains the following members, public partial class MainPage : PhoneApplicationPage {     Button FlickButton;     Image FlickImage;       FrameworkElement ElemToMove = null;     double ElemVelX, ElemVelY;       const double SPEED_FACTOR = 60;       DispatcherTimer timer; FlickButton and FlickImage are the controls that we’ll add to the canvas. ElemToMove, ElemVelX and ElemVelY will be used by the timer callback to move the ui control. SPEED_FACTOR is used to scale the velocities of ui controls. Here’s the Mainpage constructor, // Constructor public MainPage() {     InitializeComponent();       AddButtonToCanvas();       AddImageToCanvas();       timer = new DispatcherTimer();     timer.Interval = TimeSpan.FromMilliseconds(35);     timer.Tick += new EventHandler(OnTimerTick); } We’ll look at those AddButton and AddImage functions in a moment. The constructor initializes a timer which fires every 35 milliseconds, this timer will be started after the flick gesture completes with some inertia. Back to AddButton and AddImage functions, void AddButtonToCanvas() {     LinearGradientBrush brush;     GradientStop stop1, stop2;       Random rand = new Random(DateTime.Now.Millisecond);       FlickButton = new Button();     FlickButton.Content = "";     FlickButton.Width = 100;     FlickButton.Height = 100;       brush = new LinearGradientBrush();     brush.StartPoint = new Point(0, 0);     brush.EndPoint = new Point(0, 1);       stop1 = new GradientStop();     stop1.Offset = 0;     stop1.Color = Colors.White;       stop2 = new GradientStop();     stop2.Offset = 1;     stop2.Color = (Application.Current.Resources["PhoneAccentBrush"] as SolidColorBrush).Color;       brush.GradientStops.Add(stop1);     brush.GradientStops.Add(stop2);       FlickButton.Background = brush;       Canvas.SetTop(FlickButton, rand.Next(0, 400));     Canvas.SetLeft(FlickButton, rand.Next(0, 200));       MainCanvas.Children.Add(FlickButton);       //subscribe to events     FlickButton.ManipulationDelta += new EventHandler<ManipulationDeltaEventArgs>(OnManipulationDelta);     FlickButton.ManipulationCompleted += new EventHandler<ManipulationCompletedEventArgs>(OnManipulationCompleted); } this function is basically glorifying a simple task. After creating the button and setting its height and width, its background is set to a linear gradient brush. The direction of the gradient is from top towards bottom and notice that the second stop color is the PhoneAccentColor, which changes along with the theme of the device. The line,     stop2.Color = (Application.Current.Resources["PhoneAccentBrush"] as SolidColorBrush).Color; does the magic of extracting the PhoneAccentBrush from application’s resources, getting its color and assigning it to the gradient stop. AddImage function is straight forward in comparison, void AddImageToCanvas() {     Random rand = new Random(DateTime.Now.Millisecond);       FlickImage = new Image();     FlickImage.Source = new BitmapImage(new Uri("/images/Marble.png", UriKind.Relative));       Canvas.SetTop(FlickImage, rand.Next(0, 400));     Canvas.SetLeft(FlickImage, rand.Next(0, 200));       MainCanvas.Children.Add(FlickImage);       //subscribe to events     FlickImage.ManipulationDelta += new EventHandler<ManipulationDeltaEventArgs>(OnManipulationDelta);     FlickImage.ManipulationCompleted += new EventHandler<ManipulationCompletedEventArgs>(OnManipulationCompleted); } The ManipulationDelta and ManipulationCompleted handlers are same for both the button and the image. OnManipulationDelta() should look familiar, a similar implementation was used in the previous post, void OnManipulationDelta(object sender, ManipulationDeltaEventArgs args) {     FrameworkElement Elem = sender as FrameworkElement;       double Left = Canvas.GetLeft(Elem);     double Top = Canvas.GetTop(Elem);       Left += args.DeltaManipulation.Translation.X;     Top += args.DeltaManipulation.Translation.Y;       //check for bounds     if (Left < 0)     {         Left = 0;     }     else if (Left > (MainCanvas.ActualWidth - Elem.ActualWidth))     {         Left = MainCanvas.ActualWidth - Elem.ActualWidth;     }       if (Top < 0)     {         Top = 0;     }     else if (Top > (MainCanvas.ActualHeight - Elem.ActualHeight))     {         Top = MainCanvas.ActualHeight - Elem.ActualHeight;     }       Canvas.SetLeft(Elem, Left);     Canvas.SetTop(Elem, Top); } all it does is calculate the control’s position, check for bounds and then set the top and left of the control. OnManipulationCompleted() is more interesting because here we need to check if the gesture completed with any inertia and if it did, start the timer and continue to move the ui control until it comes to a halt slowly, void OnManipulationCompleted(object sender, ManipulationCompletedEventArgs args) {     FrameworkElement Elem = sender as FrameworkElement;       if (args.IsInertial)     {         ElemToMove = Elem;           Debug.WriteLine("Linear VelX:{0:0.00}  VelY:{1:0.00}", args.FinalVelocities.LinearVelocity.X,             args.FinalVelocities.LinearVelocity.Y);           ElemVelX = args.FinalVelocities.LinearVelocity.X / SPEED_FACTOR;         ElemVelY = args.FinalVelocities.LinearVelocity.Y / SPEED_FACTOR;           timer.Start();     } } ManipulationCompletedEventArgs contains a member, IsInertial, which is set to true if the manipulation was completed with some inertia. args.FinalVelocities.LinearVelocity.X and .Y will contain the velocities along the X and Y axis. We need to scale down these values so they can be used to increment the ui control’s position sensibly. A reference to the ui control is stored in ElemToMove and the velocities are stored as well, these will be used in the timer callback to access the ui control. And finally, we start the timer. The timer callback function is as follows, void OnTimerTick(object sender, EventArgs e) {     if (null != ElemToMove)     {         double Left, Top;         Left = Canvas.GetLeft(ElemToMove);         Top = Canvas.GetTop(ElemToMove);           Left += ElemVelX;         Top += ElemVelY;           //check for bounds         if (Left < 0)         {             Left = 0;             ElemVelX *= -1;         }         else if (Left > (MainCanvas.ActualWidth - ElemToMove.ActualWidth))         {             Left = MainCanvas.ActualWidth - ElemToMove.ActualWidth;             ElemVelX *= -1;         }           if (Top < 0)         {             Top = 0;             ElemVelY *= -1;         }         else if (Top > (MainCanvas.ActualHeight - ElemToMove.ActualHeight))         {             Top = MainCanvas.ActualHeight - ElemToMove.ActualHeight;             ElemVelY *= -1;         }           Canvas.SetLeft(ElemToMove, Left);         Canvas.SetTop(ElemToMove, Top);           //reduce x,y velocities gradually         ElemVelX *= 0.9;         ElemVelY *= 0.9;           //when velocities become too low, break         if (Math.Abs(ElemVelX) < 1.0 && Math.Abs(ElemVelY) < 1.0)         {             timer.Stop();             ElemToMove = null;         }     } } if ElemToMove is not null, we get the top and left values of the control and increment the values with their X and Y velocities. Check for bounds, and if the control goes out of bounds we reverse its velocity. Towards the end, the velocities are reduced by 10% every time the timer callback is called, and if the velocities reach too low values the timer is stopped and ElemToMove is made null. Here’s a short video of the program, the video is a little dodgy because my display driver refuses to run the animations smoothly. The flicks aren’t always recognised but the program should run well on an actual device (or a pc with better configuration), You can download the source code from here: ButtonDragAndFlick.zip

    Read the article

  • Problem trying to lock framerate at 60 FPS

    - by shad0w
    I've written a simple class to limit the framerate of my current project. But it does not work as it should. Here is the code: void FpsCounter::Process() { deltaTime = static_cast<double>(frameTimer.GetMsecs()); waitTime = 1000.0/fpsLimit - deltaTime; frameTimer.Reset(); if(waitTime <= 0) { std::cout << "error, waittime: " << waitTime << std::endl; } else { SDL_Delay(static_cast<Uint32>(waitTime)); } if(deltaTime == 0) { currFps = -1; } else { currFps = 1000/deltaTime; } std::cout << "--Timings--" << std::endl; std::cout << "Delta: \t" << deltaTime << std::endl; std::cout << "Delay: \t" << waitTime << std::endl; std::cout << "FPS: \t" << currFps << std::endl; std::cout << "-- --" << std::endl; } Timer::Timer() { startMsecs = 0; } Timer::~Timer() { // TODO Auto-generated destructor stub } void Timer::Start() { started = true; paused = false; Reset(); } void Timer::Pause() { if(started && !paused) { paused = true; pausedMsecs = SDL_GetTicks() - startMsecs; } } void Timer::Resume() { if(paused) { paused = false; startMsecs = SDL_GetTicks() - pausedMsecs; pausedMsecs = 0; } } int Timer::GetMsecs() { if(started) { if(paused) { return pausedMsecs; } else { return SDL_GetTicks() - startMsecs; } } return 0; } void Timer::Reset() { startMsecs = SDL_GetTicks(); } The "FpsCounter::Process()" Method is called everytime at the end of my gameloop. I've got the problem that the loop is correctly delayed only every second frame, so it runs one frame delayed at 60 FPS and the next without delay at over 1000 fps. I am searching the error quite a while now, but I do not find it. I hope somebody can point me in the right direction.

    Read the article

  • Hanging of host network connections when starting KVM guest on bridge

    - by Chris Phillips
    Hi, I've a KVM system upon which I'm running a network bridge directly between all VM's and a bond0 (eth0, eth1) on the host OS. As such, all machines are presented on the same subnet, available outside of the box. The bond is doing mode 1 active / passive, with an arp_ip_target set to the default gateway, which has caused some issues in itself, but I can't see the bond configs mattering here myself. I'm seeing odd things most times when I stop and start a guest on the platform, in that on the host I lose network connectivity (icmp, ssh) for about 30 seconds. I don't lose connectivity on the other already running VM's though... they can always ping the default GW, but the host can't. I say "about 30 seconds" but from some tests it actually seems to be 28 seconds usually (or at least, I lose 28 pings...) and I'm wondering if this somehow relates to the bridge config. I'm not running STP on the bridge at all, and the forwarding delay is set to 1 second, path cost on the bond0 lowered to 10 and port priority of bond0 also lowered to 1. As such I don't think that the bridge should ever be able to think that bond0 is not connected just fine (as continued guest connectivity implies) yet the IP of the host, which is on the bridge device (... could that matter?? ) becomes unreachable. I'm fairly sure it's about the bridged networking, but at the same time as this happens when a VM is started there are clearly loads of other things also happening so maybe I'm way off the mark. Lack of connectivity: # ping 10.20.11.254 PING 10.20.11.254 (10.20.11.254) 56(84) bytes of data. 64 bytes from 10.20.11.254: icmp_seq=1 ttl=255 time=0.921 ms 64 bytes from 10.20.11.254: icmp_seq=2 ttl=255 time=0.541 ms type=1700 audit(1293462808.589:325): dev=vnet6 prom=256 old_prom=0 auid=42949672 95 ses=4294967295 type=1700 audit(1293462808.604:326): dev=vnet7 prom=256 old_prom=0 auid=42949672 95 ses=4294967295 type=1700 audit(1293462808.618:327): dev=vnet8 prom=256 old_prom=0 auid=42949672 95 ses=4294967295 kvm: 14116: cpu0 unimplemented perfctr wrmsr: 0x186 data 0x130079 kvm: 14116: cpu0 unimplemented perfctr wrmsr: 0xc1 data 0xffdd694a kvm: 14116: cpu0 unimplemented perfctr wrmsr: 0x186 data 0x530079 64 bytes from 10.20.11.254: icmp_seq=30 ttl=255 time=0.514 ms 64 bytes from 10.20.11.254: icmp_seq=31 ttl=255 time=0.551 ms 64 bytes from 10.20.11.254: icmp_seq=32 ttl=255 time=0.437 ms 64 bytes from 10.20.11.254: icmp_seq=33 ttl=255 time=0.392 ms brctl output of relevant bridge: # brctl showstp brdev brdev bridge id 8000.b2e1378d1396 designated root 8000.b2e1378d1396 root port 0 path cost 0 max age 19.99 bridge max age 19.99 hello time 1.99 bridge hello time 1.99 forward delay 0.99 bridge forward delay 0.99 ageing time 299.95 hello timer 0.50 tcn timer 0.00 topology change timer 0.00 gc timer 0.04 flags vnet5 (3) port id 8003 state forwarding designated root 8000.b2e1378d1396 path cost 100 designated bridge 8000.b2e1378d1396 message age timer 0.00 designated port 8003 forward delay timer 0.00 designated cost 0 hold timer 0.00 flags vnet0 (2) port id 8002 state forwarding designated root 8000.b2e1378d1396 path cost 100 designated bridge 8000.b2e1378d1396 message age timer 0.00 designated port 8002 forward delay timer 0.00 designated cost 0 hold timer 0.00 flags bond0 (1) port id 0001 state forwarding designated root 8000.b2e1378d1396 path cost 10 designated bridge 8000.b2e1378d1396 message age timer 0.00 designated port 0001 forward delay timer 0.00 designated cost 0 hold timer 0.00 flags I do see the new port listed as learning, but in line with the forward delay, only for 1 or 2 seconds when polling the brctl output on a loop. All pointers, tips or stabs in the dark appreciated.

    Read the article

  • How to fix “Install-SPSolution: Admin SVC must be running in order to create deployment timer job”

    - by ybbest
    When I try to install a SharePoint Solution using PowerShell, I got the error “How to fix Install-SPSolution: Admin SVC must be running in order to create deployment timer job”. The reason you got error is that SharePoint 2010 Administration is not started, so to fix it you just need to start the services. Problem: Solution: To fix the issues, you need to start the SharePoint 2010 Administration service. 1. Go to services control panel. 2. Start the SharePoint 2010 Administration service. 3. Rerun your PowerShell, it should fix the problem. However, you might get another problem “A deployment or retraction is already under way for the solution “*.wsp”, and only one deployment or retraction at a time is supported”, for this problem you can check my other blog here.

    Read the article

  • Framework 4 Features: Support for Timed Jobs

    - by Anthony Shorten
    One of the new features of the Oracle Utilities Application Framework V4 is the ability for the batch framework to support Timed Batch. Traditionally batch is associated with set processing in the background in a fixed time frame. For example, billing customers. Over the last few versions their has been functionality required by the products required a more monitoring style batch process. The monitor is a batch process that looks for specific business events based upon record status or other pieces of data. For example, the framework contains a fact monitor (F1-FCTRN) that can be configured to look for specific status's or other conditions. The batch process then uses the instructions on the object to determine what to do. To support monitor style processing, you need to run the process regularly a number of times a day (for example, every ten minutes). Traditional batch could support this but it was not as optimal as expected (if you are a site using the old Workflow subsystem, you understand what I mean). The Batch framework was extended to add additional facilities to support times (and continuous batch which is another new feature for another blog entry). The new facilities include: The batch control now defines the job as Timed or Not Timed. Non-Timed batch are traditional batch jobs. The timer interval (the interval between executions) can be specified The timer can be made active or inactive. Only active timers are executed. Setting the Timer Active to inactive will stop the job at the next time interval. Setting the Timer Active to Active will start the execution of the timed job. You can specify the credentials, language to view the messages and an email address to send the a summary of the execution to. The email address is optional and requires an email server to be specified in the relevant feature configuration. You can specify the thread limits and commit intervals to be sued for the multiple executions. Once a timer job is defined it will be executed automatically by the Business Application Server process if the DEFAULT threadpool is active. This threadpool can be started using the online batch daemon (for non-production) or externally using the threadpoolworker utility. At that time any batch process with the Timer Active set to Active and Batch Control Type of Timed will begin executing. As Timed jobs are executed automatically then they do not appear in any external schedule or are managed by an external scheduler (except via the DEFAULT threadpool itself of course). Now, if the job has no work to do as the timer interval is being reached then that instance of the job is stopped and the next instance started at the timer interval. If there is still work to complete when the interval interval is reached, the instance will continue processing till the work is complete, then the instance will be stopped and the next instance scheduled for the next timer interval. One of the key ways of optimizing this processing is to set the timer interval correctly for the expected workload. This is an interesting new feature of the batch framework and we anticipate it will come in handy for specific business situations with the monitor processes.

    Read the article

  • WebLogic job scheduling

    - by XpiritO
    Hello, overflowers :) I'm trying to implement a WebLogic job scheduling example, to test my cluster capabilities of fail-over on scheduled tasks (to ensure that these tasks are executed on fail over scenario). With this in mind, I've been following this example and trying to configure everything accordingly. Here are the steps I've done so far: Configured a cluster with 1 admin server (AdminServer) and 2 managed instances (Noddy and Snoopy); Set up database tables (using Oracle XE): ACTIVE and WEBLOGIC_TIMERS; Set up data source to access DB and associated it to the scheduling tasks under "Settings for cluster" "Scheduling"; Implemented a job (TimerListener) and a servlet to initialize the job scheduling, as follows: . package timedexecution; import java.io.IOException; import java.io.PrintWriter; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import commonj.timers.Timer; import commonj.timers.TimerListener; import commonj.timers.TimerManager; public class TimerServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected static void logMessage(String message, PrintWriter out){ out.write("<p>"+ message +"</p>"); System.out.println(message); } @Override public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); // out.println("<html>"); out.println("<head><title>TimerServlet</title></head>"); // try { // logMessage("service() entering try block to intialize the timer from JNDI", out); // InitialContext ic = new InitialContext(); TimerManager jobScheduler = (TimerManager)ic.lookup("weblogic.JobScheduler"); // logMessage("jobScheduler reference " + jobScheduler, out); // jobScheduler.schedule(new ExampleTimerListener(), 0, 30*1000); // logMessage("Timer scheduled!", out); // //execute this job every 30 seconds logMessage("service() started the timer", out); // logMessage("Started the timer - status:", out); // } catch (NamingException ne) { String msg = ne.getMessage(); logMessage("Timer schedule failed!", out); logMessage(msg, out); } catch (Throwable t) { logMessage("service() error initializing timer manager with JNDI name weblogic.JobScheduler " + t,out); } // out.println("</body></html>"); out.close(); } private static class ExampleTimerListener implements Serializable, TimerListener { private static final long serialVersionUID = 8313912206357147939L; public void timerExpired(Timer timer) { SimpleDateFormat sdf = new SimpleDateFormat(); System.out.println( "timerExpired() called at " + sdf.format( new Date() ) ); } } } Then I executed the servlet to start the scheduling on the first managed instance (Noddy server), which returned as expected: (Servlet execution output) service() entering try block to intialize the timer from JNDI jobScheduler reference weblogic.scheduler.TimerServiceImpl@43b4c7 Timer scheduled! service() started the timer Started the timer - status: Which resulted in the creation of 2 rows in my DB tables: WEBLOGIC_TIMERS table state after servlet execution: "EDIT"; "TIMER_ID"; "LISTENER"; "START_TIME"; "INTERVAL"; "TIMER_MANAGER_NAME"; "DOMAIN_NAME"; "CLUSTER_NAME"; ""; "Noddy_1268653040156"; "[datatype]"; "1268653040156"; "30000"; "weblogic.JobScheduler"; "myCluster"; "Cluster" ACTIVE table state after servlet execution: "EDIT"; "SERVER"; "INSTANCE"; "DOMAINNAME"; "CLUSTERNAME"; "TIMEOUT"; ""; "service.SINGLETON_MASTER"; "6382071947583985002/Noddy"; "QRENcluster"; "Cluster"; "10.03.15" Although, the job is not executed as scheduled. It should print a message on the server's log output (Noddy.out file) with a timestamp, saying that the timer had expired. It doesn't. My log files state as follows: Admin server log (myCluster.log file): ####<15/Mar/2010 10H45m GMT> <Warning> <Cluster> <test-ad> <Noddy> <[STANDBY] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <> <1268649925727> <BEA-000192> <No currently living server was found that could host TimerMaster. The server will retry in a few seconds.> Noddy server log (Noddy.out file): service() entering try block to intialize the timer from JNDI jobScheduler reference weblogic.scheduler.TimerServiceImpl@43b4c7 Timer scheduled! service() started the timer Started the timer - status: <15/Mar/2010 10H45m GMT> <Warning> <Cluster> <BEA-000192> <No currently living server was found that could host TimerMaster. The server will retry in a few seconds.> (Noddy.log file): ####<15/Mar/2010 11H24m GMT> <Info> <Common> <test-ad> <Noddy> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <> <1268652270128> <BEA-000628> <Created "1" resources for pool "TxDataSourceOracle", out of which "1" are available and "0" are unavailable.> ####<15/Mar/2010 11H37m GMT> <Info> <Cluster> <test-ad> <Noddy> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <<anonymous>> <> <> <1268653040226> <BEA-000182> <Job Scheduler created a job with ID Noddy_1268653040156 for TimerListener with description timedexecution.TimerServlet$ExampleTimerListener@2ce79a> ####<15/Mar/2010 11H39m GMT> <Info> <JDBC> <test-ad> <Noddy> <[ACTIVE] ExecuteThread: '3' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <> <1268653166307> <BEA-001128> <Connection for pool "TxDataSourceOracle" closed.> Can anyone help me out discovering what's wrong with my configuration? Thanks in advance for your help!

    Read the article

  • SecurityException when accessing (ejb2-) session bean via local interface in JBoss 5

    - by sme
    I have the following problem with an EJB 2 SessionBean when deploying in JBoss 5: The SessionBean (called LVSKeepAliveDispatcher) requires a specific user role (called "LVSUser"), specified by <method-permission > <description></description> <role-name>LVSUser</role-name> <method > <description></description> <ejb-name>LVSKeepAliveDispatcher</ejb-name> <method-name>*</method-name> </method> </method-permission> in ejb-jar.xml. I now want to access this SessionBean from a Service (i.e. a class implementing the org.jboss.varia.scheduler.Schedulable interface that is then registered as a service) running inside the same JBoss instance. This is my jboss-service.xml: <server> <mbean code="org.jboss.varia.scheduler.Scheduler" name="lvs:service=TranslationService"> <attribute name="StartAtStartup">true</attribute> <attribute name="SchedulableClass">de.repower.lvs.server.service.translation.TranslationService</attribute> <attribute name="SchedulableArguments"></attribute> <attribute name="SchedulableArgumentTypes"></attribute> <attribute name="InitialStartDate">NOW</attribute> <attribute name="SchedulePeriod">60000</attribute> <attribute name="InitialRepetitions">1</attribute> <attribute name="TimerName">jboss:service=Timer,name=TranslationServiceTimer</attribute> <depends><mbean code="javax.management.timer.Timer" name="jboss:service=Timer,name=TranslationServiceTimer"/></depends> <depends>jboss.j2ee:service=EJB,jndiName=de/repower/lvs/i18n/sessionbeans/LVSTranslation</depends> </mbean> As the service is deployed in the same vm as the session bean I want to call the session bean via the local interface, but I get a SecurityException when I try to create an instance. When instead I do a lookup of the RemoteInterface it works. This is the code inside the perform method of my service class: public void perform(Date now, long remainingRepetitions) { try { final UsernamePasswordHandler handler = new UsernamePasswordHandler(USERNAME, PASSWORD); final LoginContext lc = new LoginContext("client-login", handler); lc.login(); // Trying to instantiate an LVSKeepAliveDispatcher via remote interface // This part works LVSKeepAliveDispatcher localvHome = LVSKeepAliveDispatcherUtil.getHome().create(); LOGGER.info("Successfully instantiated an LVSKeepAliveDispatcher " + localvHome.toString()); // Trying to instantiate an LVSKeepAliveDispatcherLocal via local interface LVSKeepAliveDispatcherLocal localvLocalHome = LVSKeepAliveDispatcherUtil.getLocalHome().create(); // this code is unforunately never reached LOGGER.info("Successfully instantiated an LVSKeepAliveDispatcherLocal " + localvLocalHome.toString()); lc.logout(); } catch (final Exception ex) { LOGGER.error("Error: ", ex); } } Exception: 2009-02-17 10:38:02,266 INFO [lvsi18n] (Timer-2) Successfully instantiated an LVSKeepAliveDispatcher de/repower/lvs/server/service/alive/sessionbeans/LVSKeepAliveDispatcher:Stateless 2009-02-17 10:38:02,297 ERROR [org.jboss.ejb.plugins.SecurityInterceptor] (Timer-2) Error in Security Interceptor java.lang.SecurityException: Authentication exception, principal=internalSystemUser at org.jboss.ejb.plugins.SecurityInterceptor.checkSecurityContext(SecurityInterceptor.java:321) at org.jboss.ejb.plugins.SecurityInterceptor.process(SecurityInterceptor.java:243) at org.jboss.ejb.plugins.SecurityInterceptor.invokeHome(SecurityInterceptor.java:205) at org.jboss.ejb.plugins.security.PreSecurityInterceptor.process(PreSecurityInterceptor.java:136) at org.jboss.ejb.plugins.security.PreSecurityInterceptor.invokeHome(PreSecurityInterceptor.java:88) at org.jboss.ejb.plugins.LogInterceptor.invokeHome(LogInterceptor.java:132) at org.jboss.ejb.plugins.ProxyFactoryFinderInterceptor.invokeHome(ProxyFactoryFinderInterceptor.java:107) at org.jboss.ejb.SessionContainer.internalInvokeHome(SessionContainer.java:639) at org.jboss.ejb.Container.invoke(Container.java:1046) at org.jboss.ejb.plugins.local.BaseLocalProxyFactory.invokeHome(BaseLocalProxyFactory.java:362) at org.jboss.ejb.plugins.local.LocalHomeProxy.invoke(LocalHomeProxy.java:133) at $Proxy193.create(Unknown Source) at de.repower.lvs.server.service.translation.TranslationService.perform(TranslationService.java:68) at org.jboss.varia.scheduler.Scheduler$PojoScheduler.invoke(Scheduler.java:1267) at org.jboss.varia.scheduler.Scheduler$BaseListener.handleNotification(Scheduler.java:1235) at sun.reflect.GeneratedMethodAccessor281.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.jboss.mx.notification.NotificationListenerProxy.invoke(NotificationListenerProxy.java:153) at $Proxy87.handleNotification(Unknown Source) at javax.management.NotificationBroadcasterSupport.handleNotification(NotificationBroadcasterSupport.java:257) at javax.management.NotificationBroadcasterSupport$SendNotifJob.run(NotificationBroadcasterSupport.java:322) at javax.management.NotificationBroadcasterSupport$1.execute(NotificationBroadcasterSupport.java:307) at javax.management.NotificationBroadcasterSupport.sendNotification(NotificationBroadcasterSupport.java:229) at javax.management.timer.Timer.sendNotification(Timer.java:1234) at javax.management.timer.Timer.notifyAlarmClock(Timer.java:1203) at javax.management.timer.TimerAlarmClock.run(Timer.java:1286) at java.util.TimerThread.mainLoop(Timer.java:512) at java.util.TimerThread.run(Timer.java:462) To further diagnose the error I debugged through the SecurityInterceptor and found that in the first case (successful creating an instance via the remote interface) the security context "lvs-security" (which I defined in login-config.xml) is being used whereas in the second case (failure when creating an instance via the local interface) the generic security context "CLIENT-LOGIN" is being used. This is the definition of the securit context "lvs-security" in login-config.xml: <application-policy name = "lvs-security"> <authentication> <login-module code = "org.jboss.security.ClientLoginModule" flag = "required"> </login-module> <login-module code = "de.repower.lvs.security.UsersRolesLoginModule" flag = "sufficient"> </login-module> <login-module code = "de.repower.lvs.security.login.LVSLoginModule" flag = "required"> <module-option name = "lvs-jboss-host">localhost</module-option> <module-option name = "lvs-jboss-jndi-port">1099</module-option> </login-module> </authentication> </application-policy> I'm now kind of stuck and hope someone can give me a hint about where to further look for the cause of the problem. This worked fine in JBoss 3.2.7. Edit: My current workaround for this problem: create a new container configuration in jboss.xml and remove the security interceptor stuff from this configuration use this newly created container configuration for all my session beans that I only use locally (i.e. via local interface).

    Read the article

  • F#: Tell me what I'm missing about using Async.Parallel

    - by JBristow
    ok, so I'm doing ProjectEuler Problem #14, and I'm fiddling around with optimizations in order to feel f# out. in the following code: let evenrule n = n / 2L let oddrule n = 3L * n + 1L let applyRule n = if n % 2L = 0L then evenrule n else oddrule n let runRules n = let rec loop a final = if a = 1L then final else loop (applyRule a) (final + 1L) n, loop (int64 n) 1L let testlist = seq {for i in 3 .. 2 .. 1000000 do yield i } let getAns sq = sq |> Seq.head let seqfil (a,acc) (b,curr) = if acc = curr then (a,acc) else if acc < curr then (b,curr) else (a,acc) let pmap f l = seq { for a in l do yield async {return f a} } |> Seq.map Async.RunSynchronously let pmap2 f l = seq { for a in l do yield async {return f a} } |> Async.Parallel |> Async.RunSynchronously let procseq f l = l |> f runRules |> Seq.reduce seqfil |> fst let timer = System.Diagnostics.Stopwatch() timer.Start() let ans1 = testlist |> procseq Seq.map // 837799 00:00:08.6251990 printfn "%A\t%A" ans1 timer.Elapsed timer.Reset() timer.Start() let ans2 = testlist |> procseq pmap printfn "%A\t%A" ans2 timer.Elapsed // 837799 00:00:12.3010250 timer.Reset() timer.Start() let ans3 = testlist |> procseq pmap2 printfn "%A\t%A" ans3 timer.Elapsed // 837799 00:00:58.2413990 timer.Reset() Why does the Async.Parallel code run REALLY slow in comparison to the straight up map? I know I shouldn't see that much of an effect, since I'm only on a dual core mac. Please note that I do NOT want help solving problem #14, I just want to know what's up with my parallel code.

    Read the article

  • Application crash when using an NSTimer and pushViewController

    - by Cesar
    I'm using an NSTimer to implement a 3 seconds splash screen. If a don't use a timer the view it's correctly pushed but if I use the timer for adding a little delay the application crash with a EXC_BAD_ACCESS. I'm pretty sure the answer contains "memory management" but I can't get the point... @interface RootViewController : UIViewController { NSTimer *timer; } -(void)changeView:(NSTimer*)theTimer; @property(nonatomic,retain) NSTimer *timer; ... @implementation RootViewController @synthesize timer; - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; [[self navigationController] setNavigationBarHidden:YES]; timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(changeView:) userInfo:nil repeats:NO]; } -(void)changeView:(NSTimer*)theTimer { NSLog(@"timer fired"); //Crash here, but only if called using a timer [[self navigationController] pushViewController:list animated:YES]; }

    Read the article

  • timer_getoverrun() doesn't behave as expected when using sleep()

    - by dlp
    Here is a program that uses a POSIX per-process timer alongside the sleep subroutine. The signal used by the timer has been set to SIGUSR1 rather than SIGALRM, since SIGALRM may be used internally by sleep, but it still doesn't seem to work. I have run the program using the command line timer-overruns -d 1 -n 10000000 (1 cs interval) so, in theory, we should expect 100 overruns between calls to sigwaitinfo. However, timer_getoverrun returns 0. I have also tried a version using a time-consuming for loop to introduce the delay. In this case, overruns are recorded. Does anyone know why this happens? I am running a 3.4 Linux kernel. Program source /* * timer-overruns.c */ #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <signal.h> #include <time.h> // Signal to be used for timer expirations #define TIMER_SIGNAL SIGUSR1 int main(int argc, char **argv) { int opt; int d = 0; int r = 0; // Repeat indefinitely struct itimerspec its; its.it_interval.tv_sec = 0; its.it_interval.tv_nsec = 0; // Parse arguments while ((opt = getopt(argc, argv, "d:r:s:n:")) != -1) { switch (opt) { case 'd': // Delay before calling sigwaitinfo() d = atoi(optarg); break; case 'r': // Number of times to call sigwaitinfo() r = atoi(optarg); break; case 's': // Timer interval (seconds) its.it_interval.tv_sec = its.it_value.tv_sec = atoi(optarg); break; case 'n': // Timer interval (nanoseconds) its.it_interval.tv_nsec = its.it_value.tv_nsec = atoi(optarg); break; default: /* '?' */ fprintf(stderr, "Usage: %s [-d signal_accept_delay] [-r repetitions] [-s interval_seconds] [-n interval_nanoseconds]\n", argv[0]); exit(EXIT_FAILURE); } } // Check sanity of command line arguments short e = 0; if (d < 0) { fprintf(stderr, "Delay (-d) cannot be negative!\n"); e++; } if (r < 0) { fprintf(stderr, "Number of repetitions (-r) cannot be negative!\n"); e++; } if (its.it_interval.tv_sec < 0) { fprintf(stderr, "Interval seconds value (-s) cannot be negative!\n"); e++; } if (its.it_interval.tv_nsec < 0) { fprintf(stderr, "Interval nanoseconds value (-n) cannot be negative!\n"); e++; } if (its.it_interval.tv_nsec > 999999999) { fprintf(stderr, "Interval nanoseconds value (-n) must be < 1 second.\n"); e++; } if (e > 0) exit(EXIT_FAILURE); // Set default values if not specified if (its.it_interval.tv_sec == 0 && its.it_interval.tv_nsec == 0) { its.it_interval.tv_sec = its.it_value.tv_sec = 1; its.it_value.tv_nsec = 0; } printf("Running with timer delay %d.%09d seconds\n", (int) its.it_interval.tv_sec, (int) its.it_interval.tv_nsec); // Will be waiting for signals synchronously, so block the one in use. sigset_t sigset; sigemptyset(&sigset); sigaddset(&sigset, TIMER_SIGNAL); sigprocmask(SIG_BLOCK, &sigset, NULL ); // Create and arm the timer struct sigevent sev; timer_t timer; sev.sigev_notify = SIGEV_SIGNAL; sev.sigev_signo = TIMER_SIGNAL; sev.sigev_value.sival_ptr = timer; timer_create(CLOCK_REALTIME, &sev, &timer); timer_settime(timer, TIMER_ABSTIME, &its, NULL ); // Signal handling loop int overruns; siginfo_t si; // Make the loop infinite if r = 0 if (r == 0) r = -1; while (r != 0) { // Sleeping should cause overruns if (d > 0) sleep(d); sigwaitinfo(&sigset, &si); // Check that the signal is from the timer if (si.si_code != SI_TIMER) continue; overruns = timer_getoverrun(timer); if (overruns > 0) { printf("Timer overrun occurred for %d expirations.\n", overruns); } // Decrement r if not repeating indefinitely if (r > 0) r--; } return EXIT_SUCCESS; }

    Read the article

  • HPET for x86 BSP (how to build it for WCE8)

    - by Werner Willemsens
    Originally posted on: http://geekswithblogs.net/WernerWillemsens/archive/2014/08/02/157895.aspx"I needed a timer". That is how we started a few blogs ago our series about APIC and ACPI. Well, here it is. HPET (High Precision Event Timer) was introduced by Intel in early 2000 to: Replace old style Intel 8253 (1981!) and 8254 timers Support more accurate timers that could be used for multimedia purposes. Hence Microsoft and Intel sometimes refers to HPET as Multimedia timers. An HPET chip consists of a 64-bit up-counter (main counter) counting at a frequency of at least 10 MHz, and a set of (at least three, up to 256) comparators. These comparators are 32- or 64-bit wide. The HPET is discoverable via ACPI. The HPET circuit in recent Intel platforms is integrated into the SouthBridge chip (e.g. 82801) All HPET timers should support one-shot interrupt programming, while optionally they can support periodic interrupts. In most Intel SouthBridges I worked with, there are three HPET timers. TIMER0 supports both one-shot and periodic mode, while TIMER1 and TIMER2 are one-shot only. Each HPET timer can generate interrupts, both in old-style PIC mode and in APIC mode. However in PIC mode, interrupts cannot freely be chosen. Typically IRQ11 is available and cannot be shared with any other interrupt! Which makes the HPET in PIC mode virtually unusable. In APIC mode however more IRQs are available and can be shared with other interrupt generating devices. (Check the datasheet of your SouthBridge) Because of this higher level of freedom, I created the APIC BSP (see previous posts). The HPET driver code that I present you here uses this APIC mode. Hpet.reg [HKEY_LOCAL_MACHINE\Drivers\BuiltIn\Hpet] "Dll"="Hpet.dll" "Prefix"="HPT" "Order"=dword:10 "IsrDll"="giisr.dll" "IsrHandler"="ISRHandler" "Priority256"=dword:50 Because HPET does not reside on the PCI bus, but can be found through ACPI as a memory mapped device, you don't need to specify the "Class", "SubClass", "ProgIF" and other PCI related registry keys that you typically find for PCI devices. If a driver needs to run its internal thread(s) at a certain priority level, by convention in Windows CE you add the "Priority256" registry key. Through this key you can easily play with the driver's thread priority for better response and timer accuracy. See later. Hpet.cpp (Hpet.dll) This cpp file contains the complete HPET driver code. The file is part of a folder that you typically integrate in your BSP (\src\drivers\Hpet). It is written as sample (example) code, you most likely want to change this code to your specific needs. There are two sets of #define's that I use to control how the driver works. _TRIGGER_EVENT or _TRIGGER_SEMAPHORE: _TRIGGER_EVENT will let your driver trigger a Windows CE Event when the timer expires, _TRIGGER_SEMAPHORE will trigger a Windows CE counting Semaphore. The latter guarantees that no events get lost in case your application cannot always process the triggers fast enough. _TIMER0 or _TIMER2: both timers will trigger an event or semaphore periodically. _TIMER0 will use a periodic HPET timer interrupt, while _TIMER2 will reprogram a one-shot HPET timer after each interrupt. The one-shot approach is interesting if the frequency you wish to generate is not an even multiple of the HPET main counter frequency. The sample code uses an algorithm to generate a more correct frequency over a longer period (by reducing rounding errors). _TIMER1 is not used in the sample source code. HPT_Init() will locate the HPET I/O memory space, setup the HPET counter (_TIMER0 or _TIMER2) and install the Interrupt Service Thread (IST). Upon timer expiration, the IST will run and on its turn will generate a Windows CE Event or Semaphore. In case of _TIMER2 a new one-shot comparator value is calculated and set for the timer. The IRQ of the HPET timers are programmed to IRQ22, but you can choose typically from 20-23. The TIMERn_INT_ROUT_CAP bits in the TIMn_CONF register will tell you what IRQs you can choose from. HPT_IOControl() can be used to set a new HPET counter frequency (actually you configure the counter timeout value in microseconds), start and stop the timer, and request the current HPET counter value. The latter is interesting because the Windows CE QueryPerformanceCounter() and QueryPerformanceFrequency() APIs implement the same functionality, albeit based on other counter implementations. HpetDrvIst() contains the IST code. DWORD WINAPI HpetDrvIst(LPVOID lpArg) { psHpetDeviceContext pHwContext = (psHpetDeviceContext)lpArg; DWORD mainCount = READDWORD(pHwContext->g_hpet_va, GenCapIDReg + 4); // Main Counter Tick period (fempto sec 10E-15) DWORD i = 0; while (1) { WaitForSingleObject(pHwContext->g_isrEvent, INFINITE); #if defined(_TRIGGER_SEMAPHORE) LONG p = 0; BOOL b = ReleaseSemaphore(pHwContext->g_triggerEvent, 1, &p); #elif defined(_TRIGGER_EVENT) BOOL b = SetEvent(pHwContext->g_triggerEvent); #else #pragma error("Unknown TRIGGER") #endif #if defined(_TIMER0) DWORD currentCount = READDWORD(pHwContext->g_hpet_va, MainCounterReg); DWORD comparator = READDWORD(pHwContext->g_hpet_va, Tim0_ComparatorReg + 0); SETBIT(pHwContext->g_hpet_va, GenIntStaReg, 0); // clear interrupt on HPET level InterruptDone(pHwContext->g_sysIntr); // clear interrupt on OS level _LOGMSG(ZONE_INTERRUPT, (L"%s: HpetDrvIst 0 %06d %08X %08X", pHwContext->g_id, i++, currentCount, comparator)); #elif defined(_TIMER2) DWORD currentCount = READDWORD(pHwContext->g_hpet_va, MainCounterReg); DWORD previousComparator = READDWORD(pHwContext->g_hpet_va, Tim2_ComparatorReg + 0); pHwContext->g_counter2.QuadPart += pHwContext->g_comparator.QuadPart; // increment virtual counter (higher accuracy) DWORD comparator = (DWORD)(pHwContext->g_counter2.QuadPart >> 8); // "round" to real value WRITEDWORD(pHwContext->g_hpet_va, Tim2_ComparatorReg + 0, comparator); SETBIT(pHwContext->g_hpet_va, GenIntStaReg, 2); // clear interrupt on HPET level InterruptDone(pHwContext->g_sysIntr); // clear interrupt on OS level _LOGMSG(ZONE_INTERRUPT, (L"%s: HpetDrvIst 2 %06d %08X %08X (%08X)", pHwContext->g_id, i++, currentCount, comparator, comparator - previousComparator)); #else #pragma error("Unknown TIMER") #endif } return 1; } The following figure shows how the HPET hardware interrupt via ISR -> IST is translated in a Windows CE Event or Semaphore by the HPET driver. The Event or Semaphore can be used to trigger a Windows CE application. HpetTest.cpp (HpetTest.exe)This cpp file contains sample source how to use the HPET driver from an application. The file is part of a separate (smart device) VS2013 solution. It contains code to measure the generated Event/Semaphore times by means of GetSystemTime() and QueryPerformanceCounter() and QueryPerformanceFrequency() APIs. HPET evaluation If you scan the internet about HPET, you'll find many remarks about buggy HPET implementations and bad performance. Unfortunately that is true. I tested the HPET driver on an Intel ICH7M SBC (release date 2008). When a HPET timer expires on the ICH7M, an interrupt indeed is generated, but right after you clear the interrupt, a few more unwanted interrupts (too soon!) occur as well. I tested and debugged it for a loooong time, but I couldn't get it to work. I concluded ICH7M's HPET is buggy Intel hardware. I tested the HPET driver successfully on a more recent NM10 SBC (release date 2013). With the NM10 chipset however, I am not fully convinced about the timer's frequency accuracy. In the long run - on average - all is fine, but occasionally I experienced upto 20 microseconds delays (which were immediately compensated on the next interrupt). Of course, this was all measured by software, but I still experienced the occasional delay when both the HPET driver IST thread as the application thread ran at CeSetThreadPriority(1). If it is not the hardware, only the kernel can cause this delay. But Windows CE is an RTOS and I have never experienced such long delays with previous versions of Windows CE. I tested and developed this on WCE8, I am not heavily experienced with it yet. Internet forum threads however mention inaccurate HPET timer implementations as well. At this moment I haven't figured out what is going on here. Useful references: http://www.intel.com/content/dam/www/public/us/en/documents/technical-specifications/software-developers-hpet-spec-1-0a.pdf http://en.wikipedia.org/wiki/High_Precision_Event_Timer http://wiki.osdev.org/HPET Windows CE BSP source file package for HPET in MyBsp Note that this source code is "As Is". It is still under development and I cannot (and never will) guarantee the correctness of the code. Use it as a guide for your own HPET integration.

    Read the article

  • How to fix this Timer Tick Error in C#?

    - by Iman Hejazi
    I use this code to receive data from a internet address by a Timer in defined period of times. But when the timer ticks in second time an error will raised from this line: HttpWebResponse response = (HttpWebResponse)request.GetResponse(); I want to know how to fix this problem. Timer Interval: 30secs private void timer1_Tick(object sender, EventArgs e) { WebRequest request = WebRequest.Create("http://localhost/go/online.asp?prog=y&rln=" + Properties.Settings.Default.cos); request.Credentials = CredentialCache.DefaultCredentials; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); reader.Close(); dataStream.Close(); response.Close(); }

    Read the article

  • Why does waking a PC up with a timer act differently than with the power button?

    - by Dan Rasmussen
    I have a Windows 7 machine set up as a server. It has no monitor and is only accessed through remote desktop. I set up two scheduled tasks, one to put the computer to sleep at night and another to wake it up in the morning. When it's woken up from sleep via a timer, it stays awake for only a couple minutes before going back to sleep. When woken up by pushing the power button, however, it stays awake all the way until the sleep timer. Why does my PC behave differently in these two scenarios? I have set the PC not to prompt for a user's password on wake, since I worried that the login screen might follow different power rules. I tried SmartPower Configuration but had the same problems. I can provide more details if questions are asked in the comments, but I'm not sure what's relevant.

    Read the article

  • What's Bringing SharePoint 2007 Server to a hault?

    - by juanlarios
    I've been having issues with my teste environment and I'm hoping someone has run into this problem and can point me in the right direction. I noticed: SharePoint Server Memory is through the roof at times and so is the CPU usage. Most of CPU usage is a sql proccess. Running out of disk space all the time. I looked in the Logs located in the 12 hive and sure enough I have 1G log files that are hard to open because of the size. The following are the 3 error messages that are flooding my SharePoint logs:   04/05/2010 16:02:36.99     OWSTIMER.EXE (0x0B94)                       0x0BA4    Windows SharePoint Services       Timer                             5uuf    Monitorable    The previous instance of the timer job 'Variations Propagate Page Job Definition', id '{F9A73EB4-90FE-4574-AD99-B4034056F915}' for service '{F89169F9-707B-4588-9ED0-E6D399FE5E3D}' is still running, so the current instance will be skipped.  Consider increasing the interval between jobs.    04/05/2010 15:59:51.51     OWSTIMER.EXE (0x0B94)                       0x0BA4    Windows SharePoint Services       Timer                             5uuf    Monitorable    The previous instance of the timer job 'Profile Synchronization', id '{A05E3439-8DCD-449A-9D9E-46D601CACAA2}' for service '{F89169F9-707B-4588-9ED0-E6D399FE5E3D}' is still running, so the current instance will be skipped.  Consider increasing the interval between jobs.     04/05/2010 15:56:25.53     OWSTIMER.EXE (0x0B94)                       0x0BA4    Windows SharePoint Services       Timer                             5uuf    Monitorable    The previous instance of the timer job 'Scheduled Unpublish', id '{6298F93F-388D-46B9-809E-CEDBB8659661}' for service '{F89169F9-707B-4588-9ED0-E6D399FE5E3D}' is still running, so the current instance will be skipped.  Consider increasing the interval between jobs.     04/05/2010 15:54:14.73     OWSTIMER.EXE (0x0B94)                       0x0BA4    Windows SharePoint Services       Timer                             5uuf    Monitorable    The previous instance of the timer job 'Config Refresh', id '{C42DA970-3DA3-4AA2-94E5-8499C5B80A3E}' for service '{7F6D2CBE-8071-4A30-B313-7C9989FC2D87}' is still running, so the current instance will be skipped.  Consider increasing the interval between jobs.       I'm googling around but haven't found much. I know one other person posted something about this back in 2008, but no answers were reached. I have already checked the databases to see if any of them have gone offline for whatever reason, but from SQL everything is fine. I recently re-created an SSP and deleted an old ssp. So I thought maybe that was causing it, and who knows? maybe that causes some of the problems or maybe all. I'm running configuration wizard and see if anything changes. Please if someone has had similar issues let me know.

    Read the article

  • Silverlight and M-V-VM - Where should a timer live?

    - by Bill Jeeves
    I'm creating a simple monitoring tool in Silverlight. It talks to a web service to retrieve the status information and store it in the ViewModel. This needs to happen once per minute so I'm going to add a timer for this purpose (probably a DispatcherTimer). My question is, where should the timer go in an M-V-VM architecture? In the ViewModel or the View?

    Read the article

  • What's keeping this timer in scope? The anonymous method?

    - by Andy
    Ok, So I have a method which fires when someone clicks on our Icon in a silverlight application, seen below: private void Logo_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { e.Handled = true; ShowInfo(true); DispatcherTimer autoCloseTimer = new DispatcherTimer(); autoCloseTimer.Interval = new TimeSpan(0, 0, 10); autoCloseTimer.Tick +=new EventHandler((timerSender,args) => { autoCloseTimer.Stop(); ShowInfo(false); }); autoCloseTimer.Start(); } Whats meant to happen is that the method ShowInfo() opens up a box with the company info in and the dispatch timer auto closes it after said timespan. And this all works... But what I'm not sure about is because the dispatch timer is a local var, after the Logo_MouseLeftButtonUp method finishes, what is there to keep the dispatch timer referenced and not availible for GC collection before the anonymous method is fired? Is it the reference to the ShowInfo() method in the anonymous method? Just feels like some thing I should understand deeper as I can imagine with using events etc it can be very easy to create a leak with something like this. Hope this all makes sense! Andy.

    Read the article

  • How to re-enable the idle timer in ios once it has been disabled (to allow the display to sleep again)?

    - by lindon fox
    I have figured out how to stop an iOS device from going to sleep (see below), but I am having troubles undoing that setting. According to the Apple Documentation, it should just be changing the value of the idleTimerDisabled property. But when I test this, it does not work. This is how I am initially stopping the device from going to sleep: //need to switch off and on for it to work initially [UIApplication sharedApplication].idleTimerDisabled = NO; [UIApplication sharedApplication].idleTimerDisabled = YES; I would have thought that the following would do the trick: [UIApplication sharedApplication].idleTimerDisabled = NO; From the Apple Documentation: The default value of this property is NO. When most applications have no touches as user input for a short period, the system puts the device into a "sleep” state where the screen dims. This is done for the purposes of conserving power. However, applications that don't have user input except for the accelerometer—games, for instance—can, by setting this property to YES, disable the “idle timer” to avert system sleep. Important: You should set this property only if necessary and should be sure to reset it to NO when the need no longer exists. Most applications should let the system turn off the screen when the idle timer elapses. This includes audio applications. With appropriate use of Audio Session Services, playback and recording proceed uninterrupted when the screen turns off. The only applications that should disable the idle timer are mapping applications, games, or similar programs with sporadic user interaction. Has anyone come across this problem? I am testing on iOS6 and iOS5. Thanks in advance.

    Read the article

  • Marquee style progressbar in wxPython

    - by Mridang Agarwalla
    Hi, Could anyone tell me how to implement a marquee style progress bar in wxPython? As stated on MSDN: you can animate it in a way that shows activity but does not indicate what proportion of the task is complete. Thank you. I tried this but it doesn't seem to work. The timer ticks but the gauge doesn't scroll. Any help? import wx import time class MyForm(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, "Timer Tutorial 1", size=(500,500)) # Add a panel so it looks the correct on all platforms panel = wx.Panel(self, wx.ID_ANY) self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.update, self.timer) self.gauProgress = wx.Gauge(panel, range=1000, pos=(30, 50), size=(440, 20)) self.toggleBtn = wx.Button(panel, wx.ID_ANY, "Start") self.toggleBtn.Bind(wx.EVT_BUTTON, self.onToggle) def onToggle(self, event): btnLabel = self.toggleBtn.GetLabel() if btnLabel == "Start": print "starting timer..." self.timer.Start(1000) self.toggleBtn.SetLabel("Stop") else: print "timer stopped!" self.timer.Stop() self.toggleBtn.SetLabel("Start") def update(self, event): print "\nupdated: ", print time.ctime() self.gauProgress.Pulse() # Run the program if __name__ == "__main__": app = wx.PySimpleApp() frame = MyForm().Show() app.MainLoop()

    Read the article

< Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >