Thread Sleep in Classic ASP? - asp-classic

I'm doing some revision on an old app that is written in classic ASP/VbScript.
It has a feature to send out an e-mail to the members of the application, but because the member list is quite large, the server rejects new e-mails after the first hundred or so are sent.
I've written some code to make it send out e-mails in burst of 20, but this still doesn't work. I think that perhaps making it sleep for a second between burst might work properly.
However, I can't seem to find a Thread.Sleep type method in VbScript.
Is there one?

This routine waits any amount of time, and doesn't use CPU:
Function asp_Wait(nMilliseconds)
Dim oShell
'' VBS: Set oShell= Wscript.CreateObject("WScript.Shell")
'' ASP:
Set oShell= Server.CreateObject("WScript.Shell")
Call oShell.run("ping 1.1.1.1 -n 1 -w " & nMilliseconds,1,TRUE)
'' Option TRUE: Wait until ping is complete
'' 1000 milli-second wait is 1 second
End Function

there is also a good hta hack that should work. Look for the A Synthetic Sleep Function here:
http://www.mvps.org/scripting/rube/index.htm

You can use :
<html>
<head>
<title>Sleep</title>
</head>
<body>
<%
function Sleep(seconds)
set oShell = CreateObject("Wscript.Shell")
cmd = "%COMSPEC% /c timeout " & seconds & " /nobreak"
oShell.Run cmd,0,1
End function
Sleep(5)
response.write("End")
%>
</body>
</html>

Are you using CDO? Since this is tagged as classic ASP I'm guessing so.
If so if you can use
myMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing")=1 '(which is send using pickup)
instead of
myMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing")=2 '(which is send using port)
It's more reliable because it writes the email to file (usually C:\inetpub\mailroot\pickup) and IIS's SMTP server checks the folder for new mail and will retry if it fails the first time. The catch is you have to set up SMTP within the IIS snap in.

Sorry that this answer is not strictly related to the question, but in trying to answer a question, it just got way to big for comments.
#shahka, the difference is, when you are trying to connect to a DB, the code enters a "wait state", (like a callback), so no CPU time is used. It matters not about what the SESSION or THREAD is doing, it matter what ELSE the CPU/Core is doing.
For an example, find an older non-multi-core CPU. Setup your sample to sleep for 10 seconds, then run for 2-5 seconds or so, then sleep again for 10. Do that about 20,000 times. While it's running, try and use box, see just how responsive it is. Move windows around, watch the CPU usage, etc.
THAT gives you an exmaple of what's happening to this man's Web server. It becomes unresponsive, because the thread scheduler will tend to 'favor' the CPU/Core that is NOT "spun up" (as we call it). So, ALL web requests, OS operations, etc will happen on the OTHER core, thus over-loading it, giving it a feeling of being "spun up" as well.
Now, you have times when you can tight-loop a CPU and it will not matter. But, in all my years of programming, I've never found it necessary to write a tight loop like that (on purpose). Some of it comes back around to doing things the right way, and the wrong way. Doing something the wrong way will often WORK, but that does not mean it wworks CORRECTLY.
If you want a good example of this, go and pick just about any virus on the planet, and analyze it. You'll find that it order to do damage, they (virus writers) often have to do things the "wrong" way. Sure, it gets the job done, but it also breaks the virus on say, a different language version of Windows, or it crashes the whole machine negating it's purpose, etc.
Greg Hewgill was one of my early teachers about this type of stuff, and since I worked with him for many years, and supported, and later QA'ed his software, I learned a lot from him, much in the same waay I'm trying to tell you why your code sample is not good. strictly speaking, the code is fine. It works. It's well written. But, it does not FUNCTION correctly, and has adverse side effects that other, maaybe amature programmers who might be reading this looking for knowledge do not fully understand. THAT'S why I did not recommend your sample.

Not to my knowledge. You'll have to use some external code written in class VB or whatever to do it.
Or busy-wait (gak).

You know, this is one of those times that I think setting up a private MSMQ queue could be a Good Thing. Put the emails you want to send on the queue, and have a newly developed .NET service do the sending. That will free up your ASP.NET application, and allow you to manage your sendin' centrally!

This looks like a good hack:
http://www.ehow.com/how_2001270_sleep-asp-using-ado.html
The trick is to create an ADO connection object and then try to connect to a non-existant server. This will block for the duration of the connection object's timeout setting.

Be aware that IIS has a default ASP Script execution time-out default of 90 seconds, so running large scripts that send volumes of email this way will time-out unless you change the asp timeout.

var shell = Server.CreateObject("WScript.Shell");
shell.run("CHOICE /C:AB /D:A /T:1 > NUL", 1, true);

The answer is don't use the server to wait, use the client.
You can write a javascript that keeps calling Send() every second using setInterval until the queue is empty.Use an Ajax call to send one email using a server side script. Then on return of the ajax call you can also indicate in the html page that an email has been sent.

If you are using SQL Server with ASP classic you can use WAITFOR "query" to stall the script for seconds or even milliseconds:
WAITFOR DELAY '00:00:01.234' -- 1,234 ms

Related

How to automatically update time in cics

I have two questions first is the main one.
1. I was able to display date in a cics map but what i need is, i want it to be ticking i.e., it should be display everysecond updated.
2. I have a COBOL-DB2 program which automatically inserts the data from database(DB2) to a file. I want this program to be called on a timestamp basis i.e., every 1hr, 2hr, or every day.
Thank you
You can do this, but you will need to change modify traditional psuedo-conversationl approach. Instead of returning and waiting for a user event, you can start your tran after some number of seconds with your current commarea and quit. If a user event occurs in that time, you can cancel your start request, if it doesn't, you can refresh the screen timestamp and repeat.
It is kinda a pain just to get a timestamp refreshed. Doesn't make much sense to bother with unless you have a really good reason.
The DB2 stuff is plain easy. Start your tran using interval control, the same START AFTER() described above, and you can have it run hourly, or bihourly, or whatever.
I don't think that you need to modify your pseudo-conversational approach to achieve what you need. Just issue a EXEC CICS START command with a one second delay (just do this once) for a small program that just issues a Send Map (or TC Write) to the terminal facility. Ideally reserve a common area on the screen so all transactions can use a common program. At some point, when the updates are no longer required, CANCEL the START request.The way I see it, the timer update transaction will mix in nicely with you user-initiated transaction flow. If a user transaction is active when the start timer pops, the timer update program will just be delayed a little.
While this should work, you need to bear in mind that you might be driving 3,600 transactions per hour for each user. Is this feature really worth all that?
This is not possible in standard CICS using maps. The 3270 protocol does not lend itself to continually updating screens. The majority of automatic updating screens such as consoles and monitoring displays use native VTAM methods, building their own data streams.
It might be possible to do this using unformatted data, but I would not recommend it in CICS. Pseudo-conversational CICS does not have a program in control during screen display, and conversational programming is highly discouraged.
You can't really do this in CICS, which was designed for pseudo-interactive responses at best. It was designed for use on mainframes where your terminal was sent a whole page or screen, the program read the screen as received (which has some fields the user would update and if you didn't change them the terminal did not send the data back) then, the CICS transaction having taken a part of a screen containing changes, sends the response back and quits.
This makes for very efficient data entry and inquiry programs. But realize, when the program has finished processing the screen, it's quit, it's gone, and it's not even in memory any more, all the resources have been reclaimed. This allows the company to run a mainframe with 300 terminals and maybe 10 megabytes of real memory, because when the program is waiting for you to respond, it's not using any resources at all, if there are 200 people running a data entry program, they are running a re-entrant program in which all 200 of them are running the same copy of the same program and the only thing they're using is maybe 1K of writable storage per user for the part that has to read a screen or a file record and do some calculations. Think about that, 200 people are running the same program and all of them, simultaneously, are using one module that uses 20K of memory for the application - and it's the same 20K for every single one of them - and 1K each of actual read/write data.
Think about that for a moment, the first user to start that data entry program uses 20K of memory for the application, plus 1K for the writable data. Each user after that who is being processed on that program uses an additional 1K of memory, that's all. When they're sitting there looking at the terminal, all they might be using is 4 bytes in a table to tell the system there's a terminal connected. No resources are used at all.
To be able to have a screen updated on a regular basis means that something has to keep running, which is not something CICS does very well. CICS is not intended to be used for interactive processing the way a PC does because you're actually running live on the PC.
EXEC CICS ASK TIME END-EXEC to update the timestamp.
EXEC CICS SEND MAP DATA ONLY END-EXEC to update the screen.
However, using the suggested
EXEC CICS START TRANSID ('name' | namefld)
DELAY (time)
END-EXEC.
is actually the better way.

Complete Classic asp page not rendering sometimes for some users (response.buffer?)

I've got a fairly complex classic asp page that for some users doesn't render completely at some times. I wonder if the response.buffer property might have something to do with that. Would setting it to false make it more likely to render completely? I suspect it's crapping out at some point but can't reproduce it on my end.
If the client is receiving a partial page and buffering is enabled, a likely cause is the buffer limit being exceeded on the server side. In that case, disabling buffering would fix the problem. It all depends how you want the response sent - disabling buffering will send the content as and when it's written rather than waiting for the script to complete. An alternative would be to put in periodic calls to Response.Flush at sensible intervals to clear the buffer and send the content in chunks as you desire. It's difficult to be certain about a fix if you can't recreate the error; give it a try and let us know how it pans out :-).
Looks like it had something to do with running too many database connections on the page on an already congested server, near as I can figure.

What is the difference between Application("Something") and Session("Something")

While debugging a classic ASP application (and learning about classic ASP at the same time) I've encountered the following
Application("Something") = "some value"
and elsewhere in the code this value gets used thus:
someObj.Property = Session("Something")
How does the Application object relate to Session?
A Session variable is linked to a user. An Application variable is shared between all users.
Application is a handy vault for storing things you want to persist but you can't guarantee they'll always be there. So think low-end caching, short-term variable storage, etc.
In this context with these definitions, they have very little to do with each other except that getting and setting variables is roughly the same for each.
Note: there can be concurrency issues when using Application (because you could easily have more than one user hitting something that reads or writes to it) so I suggest you use Application.Lock before you write and Application.Unlock after you're done. This only really applies to writing.
Note 2: I'm not sure if it automatically unlocks after the request is done (that would be sensible) but I wouldn't trust it to. Make sure that any part of the application that could conceivable explode isn't within a lock otherwise you might face locking other users out.
Note 3: In that same vein, don't put things that take a long time to process inside a lock, only the bit where you write the data. If you do something that takes 10 seconds while in a lock, you lock everybody else out.

Asp.net sql server 2005 timeout issue

HI
We am getting time outs in our asp.net application. We are using sql server 2005 as the DB.
The queries run very fast in the query analyser . However when we check the time through the profiler it shows a time that is many times more than what we get in query analyser.
(paramter sinffing is not the cause)
Any help is much appreciated
thanks
We are on a SAN
Cleared the counters. The new counters are
ASYNC_NETWORK_IO 540 9812 375 78
WRITELOG 70 1828 328 0
The timeout happens only on a particular SP which a particular set of params. if we change the params and access the app it works fine. We ran the profiler and found that the SP batchcompleted statement comes up in the profiler after the timeout happens on asp.net side. If we restart the server everything works fine
if we remove the plan from the cache the app works fine. However we have taken into consideration parameter sniffing in the sp. what else could be the reason
If I was to take a guess, I would assume that the background database load from the webserver is elevating locks and causing the whole thing to slow down. Then you take a large-ish query and run it and that causes lock (and resource) contension.
I see this ALL THE TIME with companies complaining of performance problems with their client-server applications when going from one SQL server to a cluster. In the web-world, we get those issues much earlier.
The solution (most times) to lock issues with one of the following:
* Refactor your queries to work better (storing SCOPE_IDENTITY instead of calling it 5 times for example)
* Use the NO LOCK statement everywhere it makes sense.
EDIT:
Also, try viewing the server with the new 2008 SQL Management Studio 'Activity Monitor'. You can find it by right-clicking on your server and selecting 'Activity Monitor'.
Go to the Processes section and look at how many processes are 'waiting'. Your wait time should be near-0. If you see alot of stuff under 'Wait Type', post a screen shot and I can give you an idea of what the next step is.
Go to the Resource Waits section and see what the numbers look like there. Your waiters should always be near-0.
And 'Recent Expensive Queries' is awesome to look at to find out what you can do to improve your general performance.
Edit #2:
How much slower is it? Your SAN seems to be taking up about 10 seconds worth, but if you are talking 20 seconds vs. 360 seconds, then that would not be relevent, and there is no waits for locks, so I guess I am drawing a blank. If the differene is between 1 second and 10 seconds then it seems to be network related.
Run the following script to create this stored proc:
CREATE PROC [dbo].[dba_SearchCachedPlans]
#StringToSearchFor VARCHAR(255)
AS
/*----------------------------------------------------------------------
Purpose: Inspects cached plans for a given string.
------------------------------------------------------------------------
Parameters: #StringToSearchFor - string to search for e.g. '%<MissingIndexes>%'.
Revision History:
03/06/2008 Ian_Stirk#yahoo.com Initial version
Example Usage:
1. exec dba_SearchCachedPlans '%<MissingIndexes>%'
2. exec dba_SearchCachedPlans '%<ColumnsWithNoStatistics>%'
3. exec dba_SearchCachedPlans '%<TableScan%'
4. exec dba_SearchCachedPlans '%CREATE PROC%MessageWrite%'
-----------------------------------------------------------------------*/
BEGIN
-- Do not lock anything, and do not get held up by any locks.
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SELECT TOP 100
st.TEXT AS [SQL],
cp.cacheobjtype,
cp.objtype,
DB_NAME(st.dbid) AS [DatabaseName],
cp.usecounts AS [Plan usage],
qp.query_plan
FROM sys.dm_exec_cached_plans cp
CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) st
CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) qp
WHERE CAST(qp.query_plan AS NVARCHAR(MAX)) LIKE #StringToSearchFor
ORDER BY cp.usecounts DESC
END
Then execute:
exec dba_SearchCachedPlans '%<MissingIndexes>%'
And see if you are missing any recommended indexes.
When SQL server creates a plan it saves it, along with any recommended indexes. Just click on the query_plan column text to show you the graph. On the top there will be recommended indexes you should implement.
I don't have the answer for you, because I'm not a guru. But I do remember reading on some SQL blogs recently that SQL 2008 has some extra things you can add to the query/stored procedure so it calculates things differently. I think one thing you could try searching for is called 'hints'. Also, how SQL uses the current 'statistics' makes a difference too. Look that up. And how the execution plan is only generated for the first run--if that plan doesn't work with different parameter values because there would be a vast difference in what would be searched/returned, it can present this behavior I think.
Sorry I can't be more helpful. I'm just getting my feet wet with SQL Server performance at this level. I bet if you asked someone like Brent Ozar he could point you in the right direction.
I've had this exact same issue a couple of times before. It seemed to happen to me when a particular user was on the site when it was deployed. When that user would run certain stored procedures with their ID it would timeout. When others would run it, or I would run it from the DB, it would run in no time. We had our DBA's watch everything they could and they never had an answer. In the end, everything was fixed whenever I re-deployed the site and the user was not already logged in.
I've had similar issues and with my case it had to do with the SP recompiling. Specifically it was my use of temp tables vs table variables.

Need to test an ajax timeout condition

As the title mentions, I have a timeout callback handler on an ajax call, and I want to be able to test that condition but nothing is coming to mind immediately on ways I can force my application to hit that state, any suggestions?
You could always run a server-side script that keeps running for a period of time.
For example:
<?php
sleep(10); //sleep for 10 seconds.
print "This script has finished.";
>
First off, I think you need to be clearer in your question - what technology are you using and where is this process that is timing out - server-side or client-side?
If you want to have the server-side code take a long time and you are using .NET, place this line in the method you call server-side:
System.Threading.Thread.Sleep(timeoutMilliseconds);
As long as you use a number sufficient so that your client-side code assumes the server has timed out, you should be good.
YUI Connection Manager allows you to introduce slowdown in your Javascript to test AJAX against latency.

Resources